linux - bash 子字符串在解释器模式下工作但不在 shell 脚本中

标签 linux bash shell aix

当我尝试在解释器模式下在 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/

相关文章:

bash - 使用 Bash 计算字符串中 char 的出现次数

java - 检查远程文件是否存在 Linux

linux - 运行 Anaconda 导航器时出错

linux - xmodmap 清除命令

linux - 尝试在我的 shell 脚本中实现 CASE

linux - 如何将 bash 更改为默认值(-bash-4.1$ 到 bhargavd@ip-10-0-0-1 ~)

linux - 迭代 map 并导出变量

linux - 我如何在一组 tarball 中找到一个特定的文件?

linux - 使用 awk 在 Shell 中过滤掉 [..] 中的子字符串列

c - 管道实现