2017-07-20 34 views
0

我想將函數中指定的命令與字符串連接起來並在執行後執行。
我將簡化我的需要與爲例,執行 「ls -l命令-a」將函數與字符串連接並執行它

#!/bin/bash 

echo -e "specify command" 
read command         # ls 

echo -e "specify argument" 
read arg          # -l 

test() { 
$command $arg 
} 

eval 'test -a' 

+0

你要找的'eval'。小心使用 – Aaron

+0

定義一個函數測試不是一個好主意,因爲它是'[''shell builtin –

回答

0

使用數組,像這樣:如果你想有一個功能

args=() 

read -r command 
args+=("$command") 

read -r arg 
args+=("$arg") 

"${args[@]}" -a 

,那麼你可以這樣做:

run_with_extra_switch() { 
    "[email protected]" -a 
} 

run_with_extra_switch "${args[@]}" 
+1

好!!我用這個數組方法,它工作!謝謝 –

+0

@AnasSlim請閱讀[當某人回答我的問題時該怎麼辦?](https://stackoverflow.com/help/someone-answers)。 – SLePort

+0

我無法投票,但我指定了最佳答案。感謝您的建議 –

0
#!/bin/bash 

echo -e "specify command" 
read command         # ls 

echo -e "specify argument" 
read arg          # -l 

# using variable 
fun1() { 
    line="$command $arg" 
} 

# call the function 
fun1 
# parameter expansion will expand to the command and execute 
$line 

# or using stdout (overhead) 
fun2() { 
    echo "$command $arg" 
} 
# process expansion will execute function in sub-shell and output will be expanded to a command and executed 
$(fun2) 

它將爲給定的問題的工作然而,瞭解它是如何工作的,看看shell擴展,必須注意執行任意命令。

在執行該命令之前,可以通過printf '<%s>\n'作爲前綴來顯示執行的內容。

相關問題