简体   繁体   English

在bash中动态生成命令

[英]Dynamically generate command in bash

I want to dynamically generate pretty long bash command depending on the command line options.我想根据命令行选项动态生成很长的 bash 命令。 Here is what I tried:这是我尝试过的:

CONFIG_PATH=""

#Reading CONFIG_PATH from getopts if supplied

SOME_OPT=""
if [ ! -z "$CONFIG_PATH" ]; then
    SOME_OPT="-v -s -cp $CONFIG_PATH"
fi

some_bash_command $SOME_OPT

The point here is that I want to pass 0 arguments to the some_bash_command if no arguments were passed to the script.这里的重点是,如果没有参数传递给脚本,我想将 0 个参数传递给some_bash_command In case there were some arguments I want to pass them.如果有一些参数我想传递它们。

It works fine, but the problem is that this approach looks rather unnatural to me.它工作正常,但问题是这种方法对我来说看起来很不自然。

What would be a better yet practical way to do this?什么是更好但实用的方法来做到这一点?

Your approach is more-or-less the standard one;您的方法或多或少是标准方法; the only significant improvement that I'd recommend is to use an array , so that you can properly quote the arguments.我建议的唯一重要改进是使用array ,以便您可以正确引用参数。 (Otherwise your command can horribly misbehave if any of the arguments happen to include special characters such as spaces or asterisks.) (否则,如果任何参数碰巧包含特殊字符(如空格或星号),您的命令可能会出现可怕的错误行为。)

So:所以:

SOME_OPT=()
if [ ! -z "$CONFIG_PATH" ]; then
    SOME_OPT=(-v -s -cp "$CONFIG_PATH")
fi

some_bash_command "${SOME_OPT[@]}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM