Bash
bash zip 錯誤:無效的命令參數(不支持短選項“”)
大家好,我對這段程式碼有疑問:
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\ Little\ Non\ -\ Hanamaru\ Sensation\ (TV\ Size).zip 20060\ Little\ Non\ -\ Hanamaru\ Sensation\ (TV\ Size)/*
嘗試:
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 程式碼進行轉義的需要。
此規則的唯一例外是當您明確需要分詞或路徑名擴展時。 2. 一個例子可能會有所幫助。讓我們考慮一個包含一個文件的目錄的簡單範例:
$ 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 變數,不需要轉義。 3. shell 將行尾視為命令的結束。因此,雖然行尾的分號不會造成傷害,但它們是不必要的。