在.sh文件中使用代码时,“bash:Bad substitution”

前端之家收集整理的这篇文章主要介绍了在.sh文件中使用代码时,“bash:Bad substitution”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么
for i in *.mp4; do ffmpeg -i "$i" "${i/.mp4/.mp3}"; done

工作,如果我在控制台中使用它,但给我一个“坏替换”错误,如果我在.sh文件中使用相同的代码

for i in *.mp4
do
    ffmpeg -i "$i" "${i/.mp4/.mp3}"
done
#!/ bin / sh的含义

这是因为您在脚本中使用#!/ bin / sh,作为修复,您应该将其更改为#!/ bin / bash。

#!/bin/bash
for i in *.mp4
do
    ffmpeg -i "$i" "${i/.mp4/.mp3}"
done

当只使用一组有限的功能(由POSIX标准定义)时,人们使用#!/ bin / sh来实现最大的可移植性。 #!/ bin / bash对于用户脚本来说完美无缺。 / bin / sh通常符合符合最小POSIX标准的外壳或标准外壳(例如bash)。在后面的情况下,bash在兼容模式下运行,这在manpage中解释:

If bash is invoked with the name sh,it tries to mimic the startup behavior of historical versions of sh as closely as possible,while conforming to the POSIX standard as well.

对脚本的建议更改:

在变量(“$ i”而不是$ i)之间使用引号被认为是很好的做法。如果存储的文件名包含空格字符,引用的变量将防止出现问题。
>我喜欢你使用高级parameter expansion.我建议使用“$ {i%.mp4} .mp3”(而不是“$ {i / .mp4 / .mp3}”),因为$ {parameter%word}只能替代在最后(例如一个名为foo.mp4.backup的文件)。

原文链接:https://www.f2er.com/bash/388252.html

猜你在找的Bash相关文章