用string连接一个函数并执行它

时间:2017-07-20 12:44:03

标签: bash shell sh

  

我想用函数串联函数中指定的命令并在之后执行它   我将用一个例子来简化我的需要来执行“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'
  

除了

2 个答案:

答案 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'作为前缀来显示将要执行的内容。

答案 1 :(得分:0)

使用数组,如下所示:

args=()

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

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

"${args[@]}" -a

如果你想要一个功能,那么你可以这样做:

run_with_extra_switch () {
    "$@" -a
}

run_with_extra_switch "${args[@]}"
相关问题