2011-10-11 49 views
31

我想在bash腳本嵌入一個長的命令是這樣的:如何分解bash中極長的字符串文字?

mycommand \ 
    --server myserver \ 
    --filename extremely/long/file/name/that/i/would/like/to/be/able/to/break/up/if/possible \ 
    --otherflag \ 
    --anotherflag 

與長文件名打散。

我可以這樣做:

# Insufficiently pretty 
mycommand \ 
    --server myserver \ 
    --filename extremely/long/file/name/\ 
that/i/would/like/to/be/able/to/break/\ 
up/if/possible \ 
    --otherflag \ 
    --anotherflag \ 

,但它打破了流量。我會像能寫出這樣的:

# Doesn't work 
mycommand \ 
    --server myserver \ 
    --filename extremely/long/file/name/\ 
     that/i/would/like/to/be/able/to/break/\ 
     up/if/possible \ 
    --otherflag \ 
    --anotherflag 

但是,這並不工作,因爲它打破了字符串文字。

有沒有辦法告訴bash打破字符串文字,但忽略任何前導空格?

回答

36

你可以使用一個變量:

file=extremely/long/file/name 
file+=/that/i/would/like/to/be/able/to/break 
file+=/up/if/possible 

mycommand\ 
    --server myserver\ 
    --filename $file\ 
    --flag flag 
+6

好主意。你可以通過'+ ='運算符來代替'file = $ {file}/...' – Chriszuma

+5

+1:在我看來,這是最少混淆的方法。意圖很明確。 –

+0

@Chriszuma是的,我忘了bash允許'+ ='運算符。我編輯了我的答案。 – WilQu

36

這是一個 有點 黑客攻擊,但這個工程:

mycommand \ 
    --server myserver \ 
    --filename "extremely/long/file/name/"` 
       `"that/i/would/like/to/be/able/to/break/"` 
       `"up/if/possible" \ 
    --otherflag \ 
    --anotherflag 

猛砸符連接字符串文字是相鄰的,因此,我們採取的這種優勢。例如,echo "hi" "there"打印hi thereecho "hi""there"打印hithere

它還利用了反引號操作符,以及事實上一堆空間的評估爲無。

+2

你可以在上一行的末尾加上''''開頭,而不是''''''連續的......它保持了左邊的清潔 –

+0

良好的調用,沒有想到這一點。正式編輯。 – Chriszuma

1

基本上沒有什麼內置的bash做到這一點。
包裝通常比它的價值更麻煩,但是說,你可以嘗試一個別名或功能,例如。 j

j(){sed -e ':a;$!N;s/ *\n *//g;ta' <<<"$1"} 

echo "$(j "3 spaces 
      /hello 
      /world 
      /this 
      /is 
      /a 
      /long 
      /path 
      ")" 

# 3 spaces/hello/world/this/is/a/long/path 
3

我在bash腳本的頂部定義一個短strcat的功能和使用內嵌調用的東西分開。我有時更喜歡使用單獨的變量,因爲我可以通過命令調用來定義長文字。

function strcat() { 
    local IFS="" 
    echo -n "$*" 
} 

mycommand \ 
    --server myserver \ 
    --filename "$(strcat \ 
     extremely/long/file/name/ \ 
     that/i/would/like/to/be/able/to/break/ \ 
     up/if/possible)" \ 
    --otherflag \ 
    --anotherflag \ 

我也很喜歡這種方法時,我必須輸入值的長CSV作爲標誌參數,因爲我可以用它來避免輸入值之間的逗號:

function strjoin() { 
    local IFS="$1" 
    shift 
    echo -n "$*" 
} 

csv_args=(
    foo=hello 
    bar=world 
    "this=arg has spaces in it" 
) 
mycommand \ 
    --server myserver \ 
    --csv_args "$(strjoin , "${csv_args[@]}")" \ 
    --otherflag \ 
    --anotherflag \ 

即相當於到

mycommand \ 
    --server myserver \ 
    --csv_args "foo=hello,bar=world,this=arg has spaces in it" \ 
    --otherflag \ 
    --anotherflag \ 
1

人們也可以使用可變的陣列

file=(extremely/long/file/name 
    /that/i/would/like/to/be/able/to/break 
    /up/if/possible) 
IFS='' 

echo mycommand\ 
    --server myserver\ 
    --filename "${file[*]}"\ 
    --flag flag