bash - 如何将可选标志和参数传递给 bash 脚本?

标签 bash unix

我有一个 bash 脚本,我将参数传递给它(并通过 $1 访问)。此参数是必须处理的单个命令(即 git pull、checkout dev 等)。

我像 ./script_name git pull 一样运行我的脚本

现在,我想在我的脚本中添加一个可选标志来执行一些其他功能。因此,如果我像 ./script_name -t git pull 这样调用我的脚本,它将具有与 ./script_name git pull 不同的功能。

我如何访问这个新标志以及传入的参数。我试过使用 getopts,但似乎无法使其与传入脚本的其他非标志参数一起使用。

最佳答案

使用 getopts 确实是要走的路:

has_t_option=false
while getopts :ht opt; do
    case $opt in 
        h) show_some_help; exit ;;
        t) has_t_option=true ;;
        :) echo "Missing argument for option -$OPTARG"; exit 1;;
       \?) echo "Unknown option -$OPTARG"; exit 1;;
    esac
done

# here's the key part: remove the parsed options from the positional params
shift $(( OPTIND - 1 ))

# now, $1=="git", $2=="pull"

if $has_t_option; then
    do_something
else
    do_something_else
fi

关于bash - 如何将可选标志和参数传递给 bash 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31124009/

相关文章:

unix - 如何为集成测试配置 sendmail?

java - 使用 Java 代码中的不同引号执行 Bash 单行代码以进行 Elasticsearch 查询

ios - 尝试自动增加内部版本号 xCode(Unix 脚本)

php - 为 Apache 而不是 CLI 启用 PHP 扩展

bash - 如何强制 Git for Windows 的 bash-shell 不将路径字符串转换为 Windows 路径?

Bash 脚本,遍历文件夹中的文件失败

c++ - 从 C++ 跳到 Perl/Unix 作业

linux bash - 比较两个文件并删除具有相同结尾的重复行

linux - Bash 使用其他文件中的数据生成多个文件

linux - 'set -- $REPLY' 是做什么的?