如何将可选标志和参数传递给bash脚本?
我有一个bash脚本,我将参数传递给它(并通过$1进行访问)。此参数是必须处理的单个命令(即git pull、checkout dev等) 我像如何将可选标志和参数传递给bash脚本?,bash,unix,Bash,Unix,我有一个bash脚本,我将参数传递给它(并通过$1进行访问)。此参数是必须处理的单个命令(即git pull、checkout dev等) 我像/script\u name git pull 现在,我想在我的脚本中添加一个可选标志,以执行其他一些功能。因此,如果我像/script\u name-t git pull那样调用脚本,它将具有与/script\u name git pull不同的功能 如何访问此新标志以及传入的参数。我尝试过使用getopts,但似乎无法使它与传递到脚本中的其他非标志参
/script\u name git pull
现在,我想在我的脚本中添加一个可选标志,以执行其他一些功能。因此,如果我像/script\u name-t git pull
那样调用脚本,它将具有与/script\u 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