bash 子字符串在解释器模式下工作但不在 shell 脚本中
bash substring working in interpreter mode but not in shell script
当我尝试在解释器模式下在 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
一起。
当我尝试在解释器模式下在 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
一起。