Shahzad
Shahzad

Reputation: 2049

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")

Upvotes: 4

Views: 11837

Answers (2)

raina77ow
raina77ow

Reputation: 106385

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).

Upvotes: 7

bobah
bobah

Reputation: 18864

Try using:

#!/bin/bash

instead of

#! /bin/sh

Upvotes: 9

Related Questions