"庆典:坏替代"使用sh文件code时 [英] "bash: Bad substitution" when using code in .sh file
问题描述
为什么
为我在* .MP4;这样做的ffmpeg -i$ I$ {I / .MP4 / .MP3}; DONE
工作,如果我用它在控制台,但给我一个坏替代的错误,如果我用同样的code在sh文件?
为我在* .MP4
做
ffmpeg的-i$ I$ {I / .MP4 / .MP3}
DONE
#!/ bin / sh的的意义
这是因为你使用#!/ bin / sh的
在脚本中,作为一个修复,你应该将其更改为#!/ bin中/ bash的
。
#!/斌/庆典
因为我在* .MP4
做
ffmpeg的-i$ I$ {I / .MP4 / .MP3}
DONE
人们使用#!/ bin / sh的
时,只用了最大的可移植性一组功能有限(由POSIX标准定义)。 #!/斌/庆典
为用户脚本完全罚款。 / bin / sh的
通常是符号链接到一个最小的POSIX兼容的外壳或一个标准shell(如bash)的。在后一种情况下的bash运行在兼容模式下,这是在手册页解释:
如果bash以名称sh启动,它试图尽可能地模仿sh历史版本的启动过程,同时也遵循POSIX标准。
块引用>建议修改你的脚本:
- 您使用引号,是很好的(
$ I
而不是$ I
),它支持的文件名字以空格字符。- 我喜欢你用先进的参数扩展。我建议使用
$ {I%.MP4} .MP3
(而不是$ {I / .MP4 / .MP3}
),因为$ {参数%字}
只替换结尾(例如一个名为foo.mp4.backup
)。Why does
for i in *.mp4; do ffmpeg -i "$i" "${i/.mp4/.mp3}"; done
work, if I use it in console, but give me a "Bad substitution" error, if I use the same code in a .sh file?
for i in *.mp4 do ffmpeg -i "$i" "${i/.mp4/.mp3}" done
解决方案The meaning of
#!/bin/sh
This is because you are using
#!/bin/sh
in your script, as a fix you should change it to#!/bin/bash
.#!/bin/bash for i in *.mp4 do ffmpeg -i "$i" "${i/.mp4/.mp3}" done
People use
#!/bin/sh
when the only use a limited set of features (defined by the POSIX standard) for maximum portability.#!/bin/bash
is perfectly fine for user scripts./bin/sh
is usually symlinked to either a minimal POSIX compliant shell or to a standard shell (e.g. bash). In the later case bash is run in compatibility mode, which is explained in the 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.
Suggested changes to your script:
- It is good that you use quotes (
"$i"
instead of$i
), which supports file names with white space characters.- I like that you use advanced parameter expansion. I suggest to use
"${i%.mp4}.mp3"
(instead of"${i/.mp4/.mp3}"
), since${parameter%word}
only substitutes at the end (for example a file namedfoo.mp4.backup
).这篇关于"庆典:坏替代"使用sh文件code时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!