0

Consider this example snippet:

copy=true
model="model"
if [ ${copy} = true ] ; then
    model+="Copy"
fi
echo ${model}

I am on the following platform:

Distributor ID: Ubuntu
Description:    Ubuntu 18.04.5 LTS
Release:    18.04
Codename:   bionic

Output using sh test.sh:

test2.sh: 4: test2.sh: model+=Copy: not found ---> error
model

Output using ./test.sh:

modelCopy

I am aware of some of the differences between running the bash script using sh and ./ after reading links[1, 2]. Still, I would like to know what's wrong with the use of += operator when I use sh, why it doesn't work. I am some use-cases where I need to run the file using sh only, how can I rectify that not found error?

kkgarg
  • 1,246
  • 1
  • 12
  • 28
  • 3
    Because `sh` is not `bash`, so that means your script has a `bash` shebang but you invoke it with `sh`. the `+=` is not supported in `sh`. – Jetchisel Aug 27 '21 at 16:18
  • 3
    Your shell is probably `bash`. Without a shebang, `bash` will use itself to execute `./test.sh`. `sh`, meanwhile, is probably a link to a shell other than `bash`: the error message shown is consistent with what `dash` would do with `model+=Copy`. – chepner Aug 27 '21 at 16:19
  • So, what could be the equivalent command if I want to use `sh`? – kkgarg Aug 27 '21 at 16:26
  • 1
    The `sh` way to append to a variable is `model="${model}Copy"`. Please note that running `sh somescript` is bad practice and if something makes you do that, then you should fix that situation (it's not necessarily a bad idea to make this a `sh` script instead of a `bash` script, but you should still avoid `sh somescript`) – that other guy Aug 27 '21 at 16:52
  • @thatotherguy What's wrong with `sh somescript` if the script is POSIX-compliant? You're going to get the same result as if you make the script executable and use an equivalent shebang. – chepner Aug 27 '21 at 20:21
  • It's bad practice because it hardcodes the shell type and options in each invocation, instead of centralizing that information in the script itself. – that other guy Aug 27 '21 at 21:33

0 Answers0