2017-09-05 75 views
0

我想這樣執行shell命令單獨的參數(包括引號):慶典:在功能上構建的命令行的部分,將被解釋爲

convert input.png -pointsize 40 -font "$HOME/Library/Fonts/Droid Sans.ttf" \ 
-background black -fill red -stroke blue label:"Foo Bar" \ 
-gravity center -composite output.png 

但它是一個腳本的一部分,有些內容是動態,我從一個函數中獲得。基本上,我想是這樣的:

function GetTextCommands { 
    echo "-pointsize $2 -font \"$HOME/Library/Fonts/$1.ttf\" \ 
    -background black -fill red -stroke blue label:\"$3\" \ 
    -gravity center -composite" 
} 

bla=$(GetTextCommands "Droid Sans" 40 "Foo Bar") 
convert input.png $bla output.png 

不過,我不斷收到這種報價相關的麻煩。要麼它不承認Sans.ttf部分,認爲這是一個不同的論點。或者,如果我在convert命令的$bla變量周圍加上引號,它會將整個事件解釋爲一個參數(當然,這當然是無效的)。

請注意,如果我在convert命令之前放置echo以預覽我的命令行的實際外觀,它看起來與我打算的方式完全相同。但是我意識到當整條線路被回顯時,一些引用可能會消失。

這是怎麼回事?

回答

2

一個正確的做法是讓你的函數填充一個包含參數的全局數組:

getTextCommands() { 
    args=(
     -pointsize "$2" 
     -font "$HOME/Library/Fonts/$1.ttf" 
     -background black 
     -fill red 
     -stroke blue 
     "label:$3" 
     -gravity center 
     -composite 
    ) 
} 

getTextCommands "Droid Sans" 40 "Foo Bar" 
convert input.png "${args[@]}" output.png 

一個缺點是使用getTextCommands要求你知道它設置的變量的名稱。

+0

謝謝,用這種方式使用數組非常整齊! – RocketNuts

3

而不是試圖產生一個字符串來執行(這將需要傳遞給eval,也許你正在尋找解決的方法就是調用eval convert input.png "$bla" output.png,但也有陷阱,所以我不建議這樣做),只是使呼叫你的函數:

function ExecTextCommands { 
    convert input.png "$1" -pointsize "$2" -font "$HOME/Library/Fonts/$1.ttf" \ 
    -background black -fill red -stroke blue label:"$3" \ 
    -gravity center -composite output.png 
} 

ExecTextCommands "Droid Sans" 40 "Foo Bar" 
+0

是的,我認爲這是很好,但我上面的例子實際上是一個更復雜的情況,在那裏我有_multiple_變量部件在命令行中,從_multiple_功能來簡化版本。 'eval'聽起來很有用,但是你有沒有提到你提到的陷阱? – RocketNuts