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

Shell脚本使用getopts存储参数失败,无法传参给Python脚本求助

Shell脚本参数解析问题修正

你的脚本存在以下几处错误:

  • 帮助选项无退出逻辑:h分支仅调用usage打印帮助信息,未添加exit 0语句,用户执行脚本 -h查看帮助后会继续执行后续Python调用逻辑,不符合预期。
  • 缺少必填参数校验:未对核心必填参数(如输入fasta文件)做非空校验,用户漏传对应参数时变量值为空,不会提前报错就直接传递给下游Python脚本。
  • 传递参数未加引号:调用Python脚本时所有变量都没有用双引号包裹,如果参数值包含空格、特殊字符(如extra传多个带空格的附加参数、fasta路径包含空格),会被Shell拆分为多个参数,导致Python接收的参数顺序错位。
  • 非法选项提示输出位置错误:?分支的错误提示没有重定向到标准错误流(1>&2),不符合Shell脚本错误输出的规范。
  • 缺少默认值初始化:可选参数用户未传时变量会是空值,容易引发下游逻辑异常。

修正后完整代码

#!/bin/bash
function usage() {
    cat <<USAGE

    Usage: $0 [-f fasta] [-o output name] [-m memory] [-t time] [-n number of tasks] [-c cores] [-g gpus] [-e extra]

    Options:
        -f  fasta file
        -o  output name
        -m  memory to request
        -t  time to request
        -n  number of tasks
        -c  cores to request
        -g  gpus to request - no more than 4!
        -e  extra arguments for program
USAGE
}

# 初始化可选参数默认值,可根据实际需求调整
out_name="result"
memory="4G"
time="2h"
number="1"
cores="2"
gpus="0"
extra=""

while getopts ":f:o:m:t:n:c:g:e:h" flag
do
    case "${flag}" in
        f)
          fasta=${OPTARG}
            ;;
        o)
          out_name=${OPTARG}
            ;;
        m)
          memory=${OPTARG}
            ;;
        t)
          time=${OPTARG}
            ;;
        n)
          number=${OPTARG}
            ;;
        c)
          cores=${OPTARG}
            ;;
        g)
          gpus=${OPTARG}
            ;;
        e)
          extra=${OPTARG}
            ;;
        h)
          usage
          exit 0
            ;;
        :)
          echo "Invalid option: $OPTARG requires an argument" 1>&2
          usage
          exit 1
            ;;
        \?)
            echo "Invalid option: -$OPTARG" 1>&2
            usage
            exit 1
            ;;
    esac
done

# 校验必填参数fasta是否传入
if [ -z "${fasta}" ]; then
    echo "Error: -f fasta file is required" 1>&2
    usage
    exit 1
fi

# 所有参数加双引号,避免空格拆分
python3 /scratch/amolinav/programs/my_script_single.py \
  "${fasta}" \
  "${out_name}" \
  "${memory}" \
  "${time}" \
  "${number}" \
  "${cores}" \
  "${gpus}" \
  "${extra}"

内容的提问来源于stack exchange,提问作者Adrian Molina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:06:10