我正在将文件的最后一行读入变量。然后我想获取字符串变量的最后 X 个字符:
#!/bin/bash
someline="this is the last line content"
echo ${someline}
somepart=${someline: -5}
echo ${somepart}
Run Code Online (Sandbox Code Playgroud)
运行: sh lastchars.sh
结果:
this is the last line content
line 4: Bad substitution
Run Code Online (Sandbox Code Playgroud)
这里可能有什么问题?
ter*_*don 20
听起来你根本没有使用bash。如果我使用dash代替,我只能重现您显示的错误bash:
bash:
$ line="someline content"
$ echo ${line}
someline content
$ lastchars=${line: -5}
$ echo ${lastchars}
ntent
Run Code Online (Sandbox Code Playgroud)dash:
$ line="someline content"
echo ${line}
lastchars=${line: -5}
echo ${lastchars}
$ someline content
$ dash: 3: Bad substitution
Run Code Online (Sandbox Code Playgroud)您的shebang 行指向bash,但您正在使用 运行脚本sh,因此忽略 shebang。/bin/sh在 Ubuntu 系统上实际上是dash一个最小的 shell,它不支持您尝试使用的语法。
使用 shebang 行时,没有理由为脚本显式调用 shell,只需使其可执行 ( chmod a+x /path/to/script.sh) 并在不指定解释器的情况下运行它:
/path/to/script.sh
Run Code Online (Sandbox Code Playgroud)
或者,只需使用正确的:
bash /path/to/script.sh
Run Code Online (Sandbox Code Playgroud)