2016-03-03 226 views
1

我有一個函數,我在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 
} 
+1

通配符「*」是bash的解決,而不是CP command.You可以使用複製「 /"\*".zip」「」 – pranav

+0

但後來我複製功能得到3個參數,而不是2 –

+0

對於bash,試試** cp $(echo $ 1)$ 2 **在腳本中 – pranav

回答

0

好了,所以我不能用我給出的建議解決這個問題。發生的事情是*在發送到函數之前擴展*,或者它在函數內部不會擴展。我嘗試了不同的方法,並最終決定重寫該函數,以支持多個參數。 通配符的擴展在發送給我的函數之前發生,並且複製函數在支持多個文件/目錄進行復制時執行之前所做的所有操作。

function Copy { 
argumentsArray=("[email protected]") 
#Check if last argument has the word exclude, in this case we must use rsync command 
if [[ ${argumentsArray[$#-1],,} == exclude:* ]]; then 
    mkdir -p "$2" 
    #get file name from the argument 
    excludeFile=${3#*:} 
    rsync -arv --exclude-from="$excludeFile" "$1" "$2" 
    if [ $? -ne 0 ]; then 
     echo "Error while to copy $1 to $2" 
     exit 1 
    fi 
else 
    mkdir -p "${argumentsArray[$#-1]}" 

    if [[ -d $1 ]]; then 
     cp -r "${argumentsArray[@]}" 
     if [ $? -ne 0 ]; then 
      exit 1 
     fi 
    else 
     cp "${argumentsArray[@]}" 
     if [ $? -ne 0 ]; then 
      exit 1 
     fi 
    fi 
fi 
} 
+0

GNU'cp'命令支持以'-t'爲目標目錄傳遞你的場景。 – tripleee

+0

另外,寫出'foo'的慣用方式;如果[$? -ne 0];那麼...'是'如果! FOO;那麼......' – tripleee

+0

@tripleee你的意思是寫下類似if! cp「$ {argumentsArray [@]}」;然後退出1 –