我有一個函數,我在bash中寫了一個拷貝文件的函數。 它的寫法是,讓我們把使用xcopy的批處理腳本轉換成bash腳本將會不那麼痛苦。這是因爲Linux中的複製命令有點不同。 這個函數做了幾件事:cp命令無法解析其中有通配符的路徑
- 它創建一個路徑到目標目錄,如果它還不存在。
- 它使用
cp
複製文件 - 它使用
cp -r
複製目錄。 - 它使用
rsync -arv --exclude-from=<FILE>
複製所有文件和文件夾中,這個目錄只是在FILE
的問題是,當我嘗試使用*
文件複製它給我的錯誤中列出的文件/文件夾:
cp: cannot stat 'some dir with * in it': No such file or directory.
我發現我可以改爲寫這樣的東西:cp "<dir>/"*".<extension>" "<targetDir>"
和命令本身的作品。但是,當我嘗試將它傳遞給我的函數時,它會得到3個參數,而不是2. 如何在我的函數中使用cp
命令,同時能夠在其中傳遞帶有通配符的路徑?這意味着參數將有雙引號在路徑的開始和他們的目的,例如:Copy "<somePath>/*.zip" "<targetDir>"
function Copy {
echo "number of args is: $#"
LastStringInPath=$(basename "$2")
if [[ "$LastStringInPath" != *.* ]]; then
mkdir -p "$2"
else
newDir=$(dirname "$2")
mkdir -p "newDir"
fi
if [ "$#" == "2" ]; then
echo "Copying $1 to $2"
if [[ -d $1 ]]; then
cp -r "$1" "$2"
else
cp "$1" "$2"
fi
if [ $? -ne 0 ]; then
echo "Error $? while trying to copy $1 to $2"
exit 1
fi
else
rsync -arv --exclude-from="$3" "$1" "$2"
if [ $? -ne 0 ]; then
echo "Error $? while trying to copy $1 to $2"
exit 1
fi
fi
}
通配符「*」是bash的解決,而不是CP command.You可以使用複製「 /"\*".zip」「」 –
pranav
但後來我複製功能得到3個參數,而不是2 –
對於bash,試試** cp $(echo $ 1)$ 2 **在腳本中 – pranav