2017-07-20 6 views
0

関数で指定されたコマンドを文字列に連結してから実行したいと思います。
私はそれがしかし、与えられた質問のために働くの "ls -l -a" にその関数を文字列と連結して実行する

+0

をあなたは 'eval'を探しています。ケアで使用する場合は、 – Aaron

+0

関数テストを定義するのは良いことではありません。 '['シェル組み込み –

答えて

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

Fine !!私はこの配列メソッドを使用して、それは働いていた!ありがとうございます –

+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) 

除き

#!/bin/bash 

echo -e "specify command" 
read command         # ls 

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

test() { 
$command $arg 
} 

eval 'test -a' 

を実行するためのexempleと私の必要性を簡素化しますそれがどのように動作しているかを理解し、シェルの拡張を見て、任意のコマンドを実行するために注意を払う必要があります。

コマンドを実行する前に、たとえば実行するものを示すために、コマンドの前にprintf '<%s>\n'を付けることができます。

関連する問題