如何通过getopts参数传递命令并执行它?

时间:2019-07-20 06:56:09

标签: arrays bash command-line-arguments execution getopts

我正在尝试制作一些应用程序,但是在这里很难描述,因此我将问题简化为简单的问题。

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

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

script.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

test.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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

无评估的解决方案:

#!/usr/bin/env bash

time=1
command=""
while getopts "t:x:" opt; do
  case "${opt}" in
    t)
      time="${OPTARG}"
      ;;
    x)
      command="${OPTARG}" # get the command

      # shift out already processed arguments
      shift "$(( OPTIND - 1 ))"
      # and exit the getopts loop, so remaining arguments
      # are passed to the command
      break
      ;;
    *) exit 1 ;; # Unknown option
  esac
done

sleep "${time}"
"${command}" "${@}" # execute the command with its arguments