Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

/bin/dash: Bad substitution

I need to do a string manipuilation in shell script (/bin/dash):

#!/bin/sh

PORT="-p7777"
echo $PORT
echo ${PORT/p/P}

the last echo fails with Bad substitution. When I change shell to bash, it works:

#!/bin/bash

PORT="-p7777"
echo $PORT
echo ${PORT/p/P}

How can I implement the string substitution in dash ?

like image 559
Martin Vegter Avatar asked Dec 11 '25 08:12

Martin Vegter


1 Answers

The substitution you're using is not a basic POSIX feature (see here, in section 2.6.2 Parameter Expansion), and dash doesn't implement it.

But you can do it with any of a number of external helpers; here's an example using sed:

PORT="-p7777"
CAPITOLPORT=$(printf '%s\n' "$PORT" | sed 's/p/P/')
printf '%s\n' "$CAPITOLPORT"

BTW, note that I'm using printf '%s\n' instead of echo -- that's because some implementations of echo do unpredictable things when their first argument starts with "-". printf is a little more complicated to use (you need a format string, in this case %s\n) but much more reliable. I'm also double-quoting all variable references ("$PORT" instead of just $PORT), to prevent unexpected parsing.

I'd also recommend switching to lower- or mixed-case variables. There are a large number of all-caps variable that have special meanings, and if you accidentally use one of those it can cause problems.

like image 194
Gordon Davisson Avatar answered Dec 13 '25 00:12

Gordon Davisson