如何在shell脚本中使用for循环

sirbozc5  于 2022-12-13  发布在  Shell
关注(0)|答案(2)|浏览(182)

这是shell脚本代码

if [ -z "$1" ]
then
  echo "src directory will be considered for analysis"  
  ${PYTHON3_ENV} $sca_wrapper_path/astree_launcher/create_astree_config.py ${prjRoot} ${OUTDIR} ${prjRoot}/src
else
  echo "Dax file will be created for the selected folders"
  ${PYTHON3_ENV} -m pip install -r ${SCA_WRAPPER_PATH}/requirements.txt
 set +u
  # optional argument. In case arguments are not provided, empty string will be set intentionally
  export SCA_include1=$2
  export SCA_include2=$3
  export SCA_include3=$4
  export SCA_include4=$5
  export SCA_include5=$6
  export SCA_include6=$7
  export SCA_include7=$8
  export SCA_include8=$9
  set -u
  ${PYTHON3_ENV} $sca_wrapper_path/astree_launcher/create_astree_config.py ${OPTION1} ${prjRoot} ${OUTDIR} ${SCA_include1} ${SCA_include2} ${SCA_include3} ${SCA_include4} ${SCA_include5} ${SCA_include6} ${SCA_include7} ${SCA_include8}
fi

在这个Bash脚本中我可以使用for循环吗

export SCA_include1=$2
      export SCA_include2=$3
      export SCA_include3=$4
      export SCA_include4=$5
      export SCA_include5=$6
      export SCA_include6=$7
      export SCA_include7=$8
      export SCA_include8=$9

并减少行数,请帮助我

5us2dqdw

5us2dqdw1#

通常,通过"$@"访问所有位置参数,"$@"扩展到每个位置参数(如果没有位置参数,则扩展到空字符串)。

if [ -n "$1" ]; then
    echo "Dax file will be created for the selected folders"
    ${PYTHON3_ENV} -m pip install -r ${SCA_WRAPPER_PATH}/requirements.txt
    option1=$1  # This is my guess as to what OPTION1 is
    shift       # remove $1 so that "$@" does not repeat it
    if test $# -lt 8; then
        echo 'You must pass at least 8 arguments' >&2
        exit 1
    fi
else
    echo "src directory will be considered for analysis"
    unset option1
    unset outdir
    set -- "${prjRoot}/src"  # Append $prjRoot/src so that "$@" expands to "${prjRoot}/src"
fi

# See discussion below on quoting
${PYTHON3_ENV} $sca_wrapper_path/astree_launcher/create_astree_config.py \
    ${option1:+"$option1"} "${prjRoot}" ${outdir:+"$outdir"} "$@"

请注意,原始代码使用set -u来确保设置了特定数量的位置参数。这种类型的检查可以通过计算$#来完成。
还要注意,这里的引号很重要。通常,最好的做法是将变量用双引号引起来,上面的命令几乎肯定会将${prjRoot}用引号引起来,但是您 * 不能 * 简单地将${option1}${outdir}用引号引起来,因为您希望它们展开为空。传递空字符串作为参数与根本不传递参数是非常不同的。上面的代码使用了${option1:+"$option1"},它可以扩展为空字符串(因此根本不传递任何参数),或$option1的引用值(这样就可以抑制字段拆分,只传递一个参数)。我怀疑outdiroption1可以更干净地处理,但是您还没有显示完整的代码,所以很难确定。如果${prjRoot}为空,我不清楚应该如何处理它,所以我假设在脚本的前面已经处理了这些情况(例如,通过异常终止并显示错误消息)。

k4emjkb1

k4emjkb12#

试试看:

for i in {2..9}; do
    export "SCA_include$((i-1))=${!i}"
done

相关问题