大家好,我对这段代码有疑问:
for dir in ~/Documents/CMDsh/*/ # list directories in the form "/tmp/dirname/"
do
countFolder=$((countFolder+1));
#echo $dir; #res: /home/arutosio/Documents/CMDsh/20060 Little Non - Hanamaru Sensation (TV Size)/
dir=${dir%*/};#remove the trailing "/" #res: /home/arutosio/Documents/CMDsh/20060 Little Non - Hanamaru Sensation (TV Size)
nameFolder=${dir##*/}; #print everything after the final "/" #res: 20060 Little Non - Hanamaru Sensation (TV Size)
pathNameFolder="$(echo $nameFolder | sed 's/ /\\ /g')"; #res: 20060\ Little\ Non\ -\ Hanamaru\ Sensation\ (TV\ Size)
pathNameFolder="$(echo $pathNameFolder | sed 's/(/\\(/g')"; #res: 20060\ Little\ Non\ -\ Hanamaru\ Sensation\ \(TV\ Size)
pathNameFolder="$(echo $pathNameFolder | sed 's/)/\\)/g')"; #res: 20060\ Little\ Non\ -\ Hanamaru\ Sensation\ \(TV\ Size\)
echo "NumFolder: $countFolder Creating... \"$nameFolder.osz\""; # print everything after the final "/"
echo "zip -r -j -9 ~/osuLazerBeatmap/$pathNameFolder.zip $pathNameFolder/*"; #res: >
#zip -r -j -9 ~/osuLazerBeatmap/20060\ Little\ Non\ -\ Hanamaru\ Sensation\ \(TV\ Size\).zip 20060\ Little\ Non\ -\ Hanamaru\ Sensation\ \(TV\ Size\)/*
zip -r -j -9 ~/osuLazerBeatmap/$pathNameFolder.zip $pathNameFolder/*;
echo '------------------------------';
done
但是当我运行 sh 这条线时:
zip -r -j -9 ~/osuLazerBeatmap/$pathNameFolder.zip $pathNameFolder/*;
出现此错误: zip 错误:命令参数无效(不支持短选项 '\') 我尝试在终端中运行此行的结果,它正在工作: zip -r -j -9 ~/osuLazerBeatmap/20060\小\非\ -\ 花丸\ Sensation\ (TV\ Size).zip 20060\ Little\ Non\ -\ 花丸\ Sensation\ (TV\ Size)/*
答案1
尝试:
for dir in ~/Documents/CMDsh/*/
do
countFolder=$((countFolder+1))
dir=${dir%*/}
nameFolder=${dir##*/}
zip -r -j -9 ~/osuLazerBeatmap/"$nameFolder".zip "$dir"/*
echo '------------------------------';
done
笔记:
始终将对 shell 变量的引用放在双引号中。在这种情况下,这意味着替换:
zip -r -j -9 ~/osuLazerBeatmap/$nameFolder.zip $dir/*
和
zip -r -j -9 ~/osuLazerBeatmap/"$nameFolder".zip "$dir"/*
这样就无需尝试使用这三行 sed 代码进行转义。
此规则的唯一例外是当您明确想要分词或者路径名扩展。
一个例子可能会有所帮助。让我们考虑一个包含一个文件的目录的简单示例:
$ ls Sensation (TV Size)
让我们创建一个 shell 变量:
$ f='Sensation (TV Size)'
现在,让我们尝试使用不带引号的 shell 变量:
$ ls $f ls: cannot access 'Sensation': No such file or directory ls: cannot access '(TV': No such file or directory ls: cannot access 'Size)': No such file or directory
请注意,当 shell 变量被引用时,它的工作效果会好得多:
$ ls "$f" Sensation (TV Size)
通过引用 shell 变量,不需要转义。
shell 将行的结尾视为命令的结尾。因此,虽然行尾的分号没有什么坏处,但它们是不必要的。