Linux Shell脚本修改需求:参数格式与特殊字符处理求助
修改后的Shell脚本
#!/bin/bash declare pspath="" declare user="" declare password="" declare ip="" # 用while循环处理参数,避免shift导致的遍历异常 while [[ $# -gt 0 ]]; do case "$1" in --pspath=*) pspath="${1#*=}" shift ;; --user=*) user="${1#*=}" shift ;; --password=*) # 用单引号包裹密码,防止$符号被Shell解析 password="'${1#*=}'" shift ;; --ip=*) ip="${1#*=}" shift ;; *) shift ;; esac done # 拼接命令,给用户名加上单引号 command="$pspath -username '$user' -password $password -ip $ip" # 修正引号嵌套,避免语法错误 t="sudo pwsh -Command \"$command\"" echo "$t"
关键修改说明
- 修复语法错误:删除重复的
declare password="",将--ip分支移入case结构内部,改用while循环处理参数(避免for循环中shift导致的参数遍历异常) - 保留特殊字符:处理
--password参数时用单引号包裹原始值,防止$123被Shell当作变量展开 - 匹配预期格式:给
user和password的参数值加上单引号,完全符合预期输出的格式 - 修正引号嵌套:拼接
t变量时用转义双引号\"包裹command,避免引号冲突导致的语法错误
测试结果
执行原命令:
./test.sh --pspath=test.ps1 --user=test --password=test$123 --ip=0.0.0.0
输出结果:
sudo pwsh -Command "test.ps1 -username 'test' -password 'test$123' -ip 0.0.0.0"
内容的提问来源于stack exchange,提问作者aman kumar chagti
相关产品推荐
相关产品推荐

