提问人:James Starlight 提问时间:8/28/2023 更新时间:8/28/2023 访问量:66
bash:使用条件将字符串拆分为几行
bash: splitting a string over several lines with conditioning
问:
在我的 bash 脚本中,我调用了一个使用许多选项的命令,定义为 --option :
packmol-memgen --pdb "$output"/${pdb_name}_${lipid}_${distxy}A/${pdb_name}.pdb --lipids $lipid --salt --salt_c Na+ --ffprot ff14SB --fflip lipid21 --ffwat tip3p --keepligs --preoriented --distxy_fix $distxy --ratio 1 --dist_wat ${dist_wat} --parametrize --minimize
我如何正确地重写这部分代码以将每个选项写在我的 bash 脚本中的单独行上,以便我可以通过启用或禁用所选选项来轻松控制程序的执行,如下所示:
packmol-memgen
--pdb "$output"/${pdb_name}_${lipid}_${distxy}A/${pdb_name}.pdb
--lipids $lipid
#--salt_c Na+ # this option is desactivated
...
--parametrize
if [ "${min}" == 1 ]; then
--minimize # ! the option is enabled if boolean $min = 1
elif [ "${min}" == 0 ]; then
#--minimize # ! the option is desactivated if boolean $min = 0
fi
在这个例子中,我注释了最后一行包含选项(--minimize),我想通过同一bash脚本中定义的布尔条件来关闭它。
答:
3赞
Ed Morton
8/28/2023
#1
将选项存储在一个数组中,然后使用该数组调用该命令,并提供其参数:
$ opts=( foo )
$ # opts+=( bar )
$ opts+=( etc )
$ echo "${opts[@]}"
foo etc
例如,未经测试:
packmol-memgen
opts=( --pdb "$output"/${pdb_name}_${lipid}_${distxy}A/${pdb_name}.pdb )
opts+=( --lipids $lipid )
#opts+=( --salt_c Na+ ) # this option is desactivated
...
opts+=( --parametrize )
if [ "${min}" == 1 ]; then
opts+=( --minimize ) # ! the option is enabled if boolean $min = 1
elif [ "${min}" == 0 ]; then
:
#opts+=( --minimize ) # ! the option is desactivated if boolean $min = 0
fi
packmol-memgen "${opts[@]}"
顺便检查一下你的报价,见 http://shellcheck.net。
评论
1赞
James Starlight
8/28/2023
很棒的解决方案,非常感谢ED!实际上它工作得很好,唯一的小问题 elif ..当里面有注释的内容时,FI 条件不起作用。我刚刚在里面添加了一条回声消息,它工作正常!
1赞
Ed Morton
8/28/2023
别客气。如果您确实需要空构造,请使用。我更新了我的答案以表明这一点。显然,在这种情况下,您也可以摆脱整个块。:
elif
评论