bash 脚本中的错误替换错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13275983/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bad substitution error in bash script
提问by Shahzad
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
./scp.sh: 4: ./scp.sh: 替换错误
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.
有人建议我使用 bash 模式,它工作正常。但是当我通过 Python 执行相同的脚本(将脚本头更改为 bash)时,我遇到了同样的错误。
I'm calling it from Python as:
我从 Python 中调用它为:
import os
os.system(". ./scp.sh")
回答by bobah
Try using:
尝试使用:
#!/bin/bash
instead of
代替
#! /bin/sh
回答by raina77ow
The reason for this error is that two different shells are used in these cases.
此错误的原因是在这些情况下使用了两种不同的外壳。
$ . scp.shcommand will use the current shell (bash) to execute the script (without forking a sub shell).
$ . scp.shcommand 将使用当前 shell ( bash) 来执行脚本(不分叉子 shell)。
$ ./scp.shcommand will use the shell specified in that hashbang line of your script. And in your case, it's either shor dash.
$ ./scp.sh命令将使用脚本的 hashbang 行中指定的 shell。在您的情况下,它是sh或dash。
The easiest way out of it is replacing the first line with #!/bin/bash(or whatever path bashis in).
最简单的方法是用#!/bin/bash(或任何路径bash)替换第一行。

