arrays - 如何通过 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
解决方案
更改"${command[@]}"
为eval "${command[0]}"
推荐阅读
- python-3.x - 如何从少量输入图像生成更多图像用于训练?
- firebase - 无法从 Firestore 检索数据
- html - 如果字体是粗体和更小,为什么渐变背景在 Firefox 中不起作用
- vsperfmon - Visual Studio 2019 中缺少 vsperf.exe
- javascript - 如何引导一个使用 ivy 进行路由的 Angular 应用程序?
- javascript - 有没有办法可以将 Text 组件的全部内容包装在 react-native 中的父视图中?
- polymer - 聚合物 3.x 中聚合物 1.x 的“行为”对应物是什么
- hyperledger-fabric - 如何在节点链码中使用 stub.getTransient()
- python - 如何在python中配对两个元组?
- charts - 如何在谷歌饼图下写文字