Bash脚本仅输出命令不执行,如何修改使其运行目标命令?
脚本仅输出命令不执行的解决方法
我编写了如下所示的脚本,但运行该脚本时,它仅输出最终命令而不执行。请问需要在脚本末尾添加什么内容才能让命令运行?
原脚本:
#!/bin/bash -l #$ -cwd # file name: singlecell.sh rundir=$1 outdir=$2 samplesheet=$3 USAGE="Usage: $0 -i [path to input run directory] -o [path to output directory] -s [path to sample sheet]" while getopts i:o:s:h opt do case "$opt" in i) RunDir="$OPTARG";; o) OutDir="$OPTARG";; s) SampSheet="$OPTARG";; h) echo $USAGE; exit 1 esac done if [[ $RunDir == "" || $OutDir == "" || $SampSheet == "" ]] then echo $USAGE exit 1 fi # asssume only one index type per run index8=`grep "SI-GA\|SI-NA" $SampSheet | wc -l` ignore="" # check if single indexes. if [ $index8 -gt 0 ]; then ignore="--filter-single-index" else ignore="--filter-dual-index" fi cmd="cellranger mkfastq --run=$RunDir --output-dir=$OutDir --csv=$SampSheet --localcores=8 --localmem=40 $ignore --barcode-mismatches=0" echo $cmd $cmd
问题原因与解决方法
你脚本里虽然写了$cmd,但直接用字符串存储命令会导致参数解析出错(比如路径含空格时),进而命令无法正确执行。正确的做法是用数组存储命令参数,而非字符串:
修正后的脚本:
#!/bin/bash -l #$ -cwd # file name: singlecell.sh rundir=$1 outdir=$2 samplesheet=$3 USAGE="Usage: $0 -i [path to input run directory] -o [path to output directory] -s [path to sample sheet]" while getopts i:o:s:h opt do case "$opt" in i) RunDir="$OPTARG";; o) OutDir="$OPTARG";; s) SampSheet="$OPTARG";; h) echo "$USAGE"; exit 1 esac done if [[ -z "$RunDir" || -z "$OutDir" || -z "$SampSheet" ]] then echo "$USAGE" exit 1 fi # assume only one index type per run index8=$(grep "SI-GA\|SI-NA" "$SampSheet" | wc -l) ignore=() # check if single indexes. if [ "$index8" -gt 0 ]; then ignore=(--filter-single-index) else ignore=(--filter-dual-index) fi # 用数组存储命令参数 cmd=( cellranger mkfastq --run="$RunDir" --output-dir="$OutDir" --csv="$SampSheet" --localcores=8 --localmem=40 "${ignore[@]}" --barcode-mismatches=0 ) # 打印命令 printf '%s ' "${cmd[@]}" echo # 执行命令 "${cmd[@]}"
关键修改点
- 将
ignore从字符串改为数组,避免参数解析时的空格分割问题 - 用数组
cmd存储整个命令的所有参数,每个参数单独一行更易维护 - 执行命令时用
"${cmd[@]}"展开数组,确保每个参数被正确传递,包括含空格的路径 - 用
$(...)替代反引号`...`,这是更现代、更安全的命令替换写法 - 用
-z判断变量是否为空,比直接比较空字符串更规范
内容的提问来源于stack exchange,提问作者pythonbeginner
相关产品推荐
相关产品推荐

