shell 脚本获取长参数

本文介绍了一种使用getopt工具解析复杂命令行参数的方法。通过示例代码,展示了如何处理包括文件路径、用户名、密码及端口号在内的多种参数,并进行参数验证。此方法适用于需要从命令行接收多个选项和参数的Shell脚本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 getopt 获取参数

# ./example.sh  abc.tar.gz  -u username -p password --port=8080
FILE=""
if [ "X$1" != "X" ];then
     FILE=$1
     if [ ! -f "$FILE" ]; then
        "${FILE} not exist!"
        exit
    fi
else
    echo -e "\e[0;32m parameter missing \e[0m"
fi

port=0
userName=""
password=""
set -- $(getopt -u -o u:p: -l port: "$@")   # -o 接收短参数, -l 接收长参数, 需要参数值的在参数后面添加: 

while [ -n "$1" ]; do
    case "$1" in
        -u) userName=$2
             shift ;;
        -p) password=$2
            shift ;;
        --port)
            port=$2
            shift 
    esac
    shift
done
echo "${userName}--${password}--port:${port}"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值