首页 > 解决方案 > 如何通过 getopts 参数传递命令并执行它?

问题描述

我正在尝试制作一些应用程序,但在这里描述它太难了,所以我将我的问题简化为更简单的问题。

我只想制作一个带有两个参数的脚本:时间和命令。它使用 getopts 解析参数,等待一段时间并执行给定的命令。

我尝试使用双引号、单引号和完全不带引号的各种组合,使用 bash 数组(我认为是这样)并寻找类似的问题,但它没有帮助。

脚本.sh

time=1
command=""
while getopts "t:x:" opt; do
  case $opt in
    t) time=$OPTARG;;
    x) command=( "$OPTARG" );; # store the command in a variable
  esac
done
sleep $time
"${command[@]}" # execute the stored command

测试.sh

# script to test arguments passing
echo "1$1 2$2 3$3 4$4"

执行脚本的结果应该与 -x 参数中传递的命令的执行结果相同。

$./script.sh -x "./test.sh a 'b c'"
1a 2'b 3c' 4 # actual results
$./test.sh a 'b c'
1a 2b c 3 4 # expected results

标签: arraysbashcommand-line-argumentsexecutiongetopts

解决方案


更改"${command[@]}"eval "${command[0]}"


推荐阅读