Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad substitution error in bash script

I have tried a lot but couldn't get the solution out of it. I have a simple script:

#! /bin/sh
o="12345"
a=o
b=${!a}
echo ${a}
echo ${b}

When executed like

$ . scp.sh

it produces the correct output with no errors, but when executed like:

$ ./scp.sh

it produces

./scp.sh: 4: ./scp.sh: Bad substitution

Any ideas why this is happening.


I was suggested to use bash mode and it works fine. But when I execute this same script through Python (changing the script header to bash), I am getting the same error.

I'm calling it from Python as:

import os
os.system(". ./scp.sh")
like image 691
Shahzad Avatar asked Dec 05 '22 13:12

Shahzad


2 Answers

Try using:

#!/bin/bash

instead of

#! /bin/sh
like image 164
bobah Avatar answered Dec 22 '22 12:12

bobah


The reason for this error is that two different shells are used in these cases.

$ . scp.sh command will use the current shell (bash) to execute the script (without forking a sub shell).

$ ./scp.sh command will use the shell specified in that hashbang line of your script. And in your case, it's either sh or dash.

The easiest way out of it is replacing the first line with #!/bin/bash (or whatever path bash is in).

like image 34
raina77ow Avatar answered Dec 22 '22 14:12

raina77ow