2013-12-09 41 views
0

我正在寫一個簡單的腳本,rsync是我的本地計算機的遠程站點,並根據命令行中指定的選項動態生成--exclude=dir標誌。如何正確傳遞運行時確定的命令行開關,其中包含*的bash?

#!/bin/bash -x 

source="[email protected]:~/public_html/live/" 
destination="wordpress/" 

exclude_flags='--exclude=cache/* ' 

if [ "$1" == "skeleton" ] ; then 
    exclude_flags+='--exclude=image-files/* ' 
fi 

rsync --archive --compress --delete $exclude_flags -e ssh $source $destination 

當我嘗試在最後一行插入$ exclude_flags變量時,我遇到了麻煩。由於變量中有空格,bash會在插值之前和之後自動插入單引號。下面是其中的bash試圖執行命令(如/ bin/bash的+ x的相關輸出):

+ /usr/bin/rsync --archive --compress --delete '--exclude=cache/*' '--exclude=image-files/*' -e /usr/bin/ssh [email protected]:~/public_html/live/ wordpress/

正如你所看到的,bash中插入了一堆單引號$的個人標記周圍exclude_flags,導致rsync嗆。

我曾嘗試:

  1. 我上面列出。

  2. 把它放在雙引號... "$exclude_flags" ...。這幾乎解決了這個問題,但並不完全。單引號只出現在$ exclude_flags的全部內容周圍,而不是圍繞每個令牌。

  3. 製作$ exclude_flags數組,然後使用$ {exclude_flags [@]}進行插值。這給出了與#2相同的輸出。

  4. 用引退引號括起整個rsync行。這給出了與#1相同的輸出。

任何想法?這看起來像是bash中一個非常簡單和常見的問題,所以我確信我做錯了什麼,但是Google根本沒有幫助。

謝謝。

+1

你是什麼rsync的「電抗器」是什麼意思?你實際上有正確的語法。順便說一句,爲了方便測試,你可以使用'--dry-run'標誌。 – janos

+1

單引號僅用於使用'-x'選項進行顯示;它們並沒有物理存在於命令行中。 – chepner

回答

0

存儲在bash變多命令行選項正確的方法是使用一個數組:

source="[email protected]:~/public_html/live/" 
destination="wordpress/" 

options=('--exclude=cache/*') 
if [[ "$1" == "skeleton" ]] ; then 
    options+=('--exclude=image-files/*') 
fi 

rsync --archive --compress --delete "${exclude_flags[@]}" -e ssh "$source" "$destination" 
相關問題