Rap*_*ael 5 scripting bash shell-script
我有一个用于我的 RaspberryPi(运行 Raspbian)的 bash 脚本,它应该将多个文件名作为参数并一个接一个地播放(使用omxplayer)。基本结构是这样的:
#!/bin/bash
for f in ${*}
do
echo "${f}";
done;
Run Code Online (Sandbox Code Playgroud)
现在当输入文件名包含空格时我遇到了问题;特别是,行为似乎不一致。假设我们有两个文件test a b并且test d e在同一个目录中。使用不同的参数运行上面的脚本会产生以下结果:
$ ./test test\ a\ b
test
a
b
$ ./test "test a b"
test
a
b
$ ./test test\ a*
test
a
b
$ ./test "test a*"
test
a*
Run Code Online (Sandbox Code Playgroud)
但是,奇怪的是:
./test "test*"
test a b
test d e
Run Code Online (Sandbox Code Playgroud)
显然,只有最后一个变体才能提供预期的输出。但是,使用起来很麻烦,特别是如果您想观看单个文件(制表符完成将填充整个名称)或者文件路径中的文件夹名称之一包含空格时。
我可以在 shellscript 中做些什么不同的事情,以便它始终按预期运行?特别是,两者
$./test test*
$./test test\ a\ b test\ d\ e
Run Code Online (Sandbox Code Playgroud)
应该产生相同的输出
test a b
test d e
Run Code Online (Sandbox Code Playgroud)
因此可以使用正常的制表符完成轻松使用该脚本。
gle*_*man 10
使用"$@"代替${*}(参见手册中的特殊参数)
for f in "$@"; do
echo make sure you quote your "$variables" everywhere in the loop
Run Code Online (Sandbox Code Playgroud)
有一个速记(更便携):
for f do ...
Run Code Online (Sandbox Code Playgroud)
for f; do 也可以在某些 shell 中工作,但不是标准的。