2016-03-08 36 views
4

我想要寫在bash的函數轉發參數cp命令。 例如: 爲輸入慶典 - 圍繞所有數組元素或參數與報價

<function> "path/with whitespace/file1" "path/with whitespace/file2" "target path" 

我想它真正做到:

cp "path/with whitespace/file1" "path/with whitespace/file2" "target path" 

但是相反,現在我實現:

cp path/with whitespace/file1 path/with whitespace/file2 target path 

我嘗試的方法到的用途是所有參數存儲在數組中,然後只與陣列運行cp命令一起。 像這樣:

function func { 
    argumentsArray=("[email protected]") 
    cp ${argumentsArray[@]} 
} 

不幸的是,就像我已經說過了,因此複製失敗,則不傳輸報價。

+0

參見[當環繞shell變量引號?](http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-外殼變量) – tripleee

回答

-4

當你寫在你的代碼"它是告訴bash「我開始一個字符串」和下一個"說:「我完成了字符串」。

由於報價是居然有隻告訴bash的東西,他們不被bash的認爲是字符串的一部分。

如果你想在字符串中的報價,你可以用\逃避它告訴bash的是字符串的一部分。

<function> "\"path with whitespace/file1\"" 
+1

他已經正確地引用了函數的自變量;他問的是如何使用函數內部的參數。 – chepner

+0

@chepner不,他不是。這正是他在功能上的問題。 cp獲取不帶引號的第一個參數,並將白色空格作爲多個參數應該是一個參數。 – selalerer

+1

因爲他沒有正確引導數組擴展。強迫用戶容納不正確的代碼是一個可怕的想法。 – chepner