当我尝试在解释器模式下在 bash shell 中执行子字符串时,我得到了预期的输出
bash-4.2$ x="SomeString"
bash-4.2$ echo $x
SomeString
bash-4.2$ y=${x:0:4}
bash-4.2$ echo $y
Some
bash-4.2$
而在 shell 脚本中运行相同的命令时,出现错误。
bash-4.2$ cat shell.sh
x="SomeString"
echo $x
y=${x:0:4}
echo $y
bash-4.2$ sh shell.sh
SomeString
shell.sh[3]: y=${x:0:4}: 0403-011 The specified substitution is not valid for this command.
bash-4.2$
具有讽刺意味的是,当我通过 bash-4.2$ ./shell.sh
调用 shell 时,它正在工作。
这里发生了什么?
我在 AIX 机器上。
最佳答案
子字符串是 bash
扩展。当您以 sh
运行它时,它会禁用此扩展。使用 bash shell.sh
即可。
您还应该将 #!/bin/bash
放在脚本的开头,以确保当您将它作为命令调用时,它会与 bash
一起运行。
关于linux - bash 子字符串在解释器模式下工作但不在 shell 脚本中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33153978/