linux shell 使用getopts进行命令行参数解析,

来源:赵克立博客 分类: Linux 标签:shell发布时间:2022-04-17 17:06:53最后更新:2022-04-17 17:07:27浏览:250
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2022-04-17 17:07:27
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

输下面代码保存成test.sh

#!/bin/bash

# ./test.sh -s deploy -d name -g xxx.git.com -t 1.0.1

step=""
site_dir=""
gitServer=""
tag=""

# getopts
while getopts "s:d:g:t:" opt; do
    case $opt in
    s) step=$OPTARG ;;
    d) site_dir=$OPTARG ;;
    g) gitServer=$OPTARG ;;
    t) tag=$OPTARG ;;
    esac
done

echo $step
echo $site_dir
echo $gitServer
echo $tag

测试

./test.sh -s deploy -d name -g xxx.git.com -t 1.0.1

2204171650186269858908.png

如果中间有参数为空的话要用引号,否则会导致解析错乱,如下

2204171650186349577647.png


正确方式

./test.sh -s deploy -d "" -g xxx.git.com -t 1.0.1

2204171650186405487300.png


微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python