这是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
并减少行数,请帮助我
通常,您可以通过"$@"
访问所有位置参数,这将扩展到每个位置参数(如果没有,则扩展到空字符串)。 您的代码段可以重写:
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
的值(因此禁止字段拆分并且只传递一个参数)。 我怀疑outdir
和option1
可以更干净地处理,但您尚未显示完整的代码,因此很难确定。 我不清楚如果${prjRoot}
为空,您应该如何处理它,所以我假设案例在脚本的前面处理(例如,通过中止并显示错误消息)。
尝试:
for i in {2..9}; do
export "SCA_include$((i-1))=${!i}"
done
${!i}
是可变的间接。 请参阅 Bash 参考手册中的外壳参数扩展。