我没有太多实际的编程经验。 我在 shell 脚本中编写了一个函数,用于获取参数,根据这些参数的值,使用其他参数调用外部程序。 (程序名称作为参数传递给函数,在本例中为 $1)。
不知怎的,我发现这段代码很糟糕,想减少行数并提高效率。我觉得这里的条件太多了,可能有更简单的方法来做到这一点。有任何想法吗?必须有更好的方法来做到这一点。谢谢。
最佳答案
您可以将参数列表构建为数组,并为列表的每个变量部分使用单独的条件(而不是像您那样嵌套条件)。这与 Roland Illig 的答案非常相似,除了使用数组而不是文本变量可以避免参数中有趣字符(如空格)可能出现的问题(参见 BashFAQ #050 )——这里可能不需要,但我更喜欢这样做这是避免以后发生意外的安全方法。另外,请注意,我假设参数必须按一定顺序排列 - 如果 -disp
可以在 `refresh
之前,那么“所有版本”部分都可以一开始就放在一起。
# Build the argument list, depending on a variety of conditions
arg_list=("-res" "$2" "$3") # all versions start this way
if [ "$7" = "allresolutions" ]; then
# allresolutions include the refresh rate parameter to be passed
arg_list+=("-refresh" "$4")
fi
arg_list+=("-disp" "$5") # all versions need the disp value
if [ "$6" = "nooptions" ]; then
: # nothing to add
elif [ "$6" = "vcaa" ]; then
arg_list+=("-vcaa" "5")
elif [ "$6" = "fsaa" ]; then
arg_list+=("-fsaa" "4")
elif [ "$6" = "vcfsaa" ]; then
arg_list+=("-vcaa" "5" "-fsaa" "4")
fi
if [ "$1" != "gears" ]; then
# ctree has time-to-run passed as parameter to account for suitable time for
# logging fps score. If bubble fps capture strategy is different from ctree,
# then this if statement has to be modified accordingly
arg_list+=("-sec" "$8")
fi
# Now actually run it
./"$1" "${arg_list[@]}" &>> ~/fps.log
关于bash - 在 shell 中,如何在不使用太多条件语句的情况下有效地处理传递给函数的参数以调用其他程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4553337/