我的bash代码有3种可能的情况。
我正在创建一个bash命令,其中有3个可能的选项,使用标志我根据输入参数为局部变量分配一个值,我的代码取决于输入参数生成一种文件,另一种文件或两个文件。
如果在命令中添加“ -r”参数,则会生成1种文件,“红色文件”,本地脚本var take, activeRed = 1
如果在命令中添加生成的“ -f”参数,“提要文件”, activeFeed = 1
如果在命令中使用“ -rf”,则生成两个文件, activeFeed = 1 activeRed = 1
if [[ $activeRed -eq 1 && $activeFeed -eq 1 ]]; then
python donwload_files.py --config config-ref-"$market".yml --path_arg $start
python donwload_files.py --config config-feed-"$market".yml --path_arg $start
elif [ $activeRed -eq 1 ];then
python donwload_files.py --config config-ref-"$market".yml --path_arg $start
elif [ $activeFeed -eq 1 ]; then
python donwload_files.py --config config-feed-"$market".yml --path_arg $start
else
python donwload_files.py --config config-ref-"$market".yml --path_arg $start
python donwload_files.py --config config-feed-"$market".yml --path_arg $start
fi
如您所见,我生成了一个非常简单的if-else语句,但是我认为有一种处理这3种情况的更有效方法,而不是这种“非可视”重复方法。
关于创建更逻辑或更有效的语句的任何想法吗?
答案 0 :(得分:2)
我认为else块是不需要的,因为那样就没有意义了。
您可以将案件数量减少到2:
if [ $activeRef -eq 1 ];then
python donwload_files.py --config config-ref-"$market".yml --path_arg $start
if [ $activeFeed -eq 1 ]; then
python donwload_files.py --config config-feed-"$market".yml --path_arg $start
您要在$ activeRef等于1时运行“ config-ref”,而在$ activeFeed等于1时运行“ config-feed”,因此无需进行更多if-else情况>
答案 1 :(得分:1)
更容易。只需独立处理每种可能性:
if [ "$activeRef" -eq 1 ]
then
python donwload_files.py --config config-ref-"$market".yml --path_arg $start
fi
if [ "$activeFeed" -eq 1 ]
then
python donwload_files.py --config config-feed-"$market".yml --path_arg $start
fi
对于您的else子句,设置activeRef
和activeFeed
变量时,请确保在未设置任何参数的情况下,必须同时设置两个变量。
if [ "$activeFeed" -ne 1 && "$activeRef" -ne 1 ]
then
activeFeed=1
activeRef=1
fi