You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 23:31:17