我想将函数中指定的命令与字符串连接起来并在执行后执行。
我将简化我的需要与为例,执行 “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'
除
我想将函数中指定的命令与字符串连接起来并在执行后执行。
我将简化我的需要与为例,执行 “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'
除
使用数组,像这样:如果你想有一个功能
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[@]}"
好!!我用这个数组方法,它工作!谢谢 –
@AnasSlim请阅读[当某人回答我的问题时该怎么办?](https://stackoverflow.com/help/someone-answers)。 – SLePort
我无法投票,但我指定了最佳答案。感谢您的建议 –
#!/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'
作为前缀来显示执行的内容。
你要找的'eval'。小心使用 – Aaron
定义一个函数测试不是一个好主意,因为它是'[''shell builtin –