如何正确使用bash -c与here-document?解决参数缺失报错问题
问题解决:bash -c 与 here-document 结合的正确用法
错误原因
你遇到的bash: -c: option requires an argument报错,是因为bash -c必须接收一个字符串形式的命令作为参数,但你的写法里-c后面没有任何命令内容,自然触发错误。
正确写法
写法1:直接让bash读取标准输入(无需-c)
这是最常用的方式,通过管道把here-document的内容传给bash,bash直接从标准输入执行命令:
cat <<- EOF | bash command1 args command2 args command3 args command4 args command5 args EOF
注:<<-中的-允许你用制表符(不是空格)缩进here-doc内的命令,缩进部分会被忽略,让代码更整洁。
写法2:将here-document内容作为bash -c的参数
如果一定要使用bash -c,可以通过命令替换把here-doc的内容转为字符串传给-c:
bash -c "$(cat <<- EOF command1 args command2 args command3 args command4 args command5 args EOF )"
这种写法会先把here-doc里的命令整合成一个字符串,再交给bash -c执行。
写法3:直接给bash -c传命令字符串(简化版)
如果不需要here-doc的缩进特性,也可以直接把命令用引号包裹传给-c,效果类似:
bash -c ' command1 args command2 args command3 args command4 args command5 args '
内容的提问来源于stack exchange,提问作者Mario Palumbo
相关产品推荐
相关产品推荐

