什么导致这个bash语法错误?

4
这个命令在命令行上运行良好...
if g++ -std=c++11 main.cpp ; then ./a.out; fi

但是当我尝试将它作为一个函数添加到我的.bashrc中时,它失败了...

function cgo() { if g++ -std=c++11 "$1" ; then ./a.out; fi }

>$ cgo main.cpp
bash: syntax error near unexpected token `main.cpp'

我在这里做错了什么?


起初这些解决方案对我没有用,但是后来我尝试打开一个新的终端,它们就可以了。现在我猜想的谜团是为什么命令“. ~/.bashrc”无法重新加载我的原始终端会话中的bashrc! - Roger Heathcote
2个回答

3
< p > } 不是特殊字符;如果你将函数定义放在一行上,你需要显式地用;终止前面的命令。

function cgo () { if g++ -std=c++11 "$1"; then ./a.out; fi; }

3
当使用{大括号}时,需要在关闭大括号之前有一个换行符或分号。对于单行代码,这意味着您需要一个分号。
function cgo() { if g++ -std=c++11 "$1" ; then ./a.out; fi; }
# ........................................................^

文档:https://www.gnu.org/software/bash/manual/bashref.html#Command-Grouping

这是一个关于命令分组的技术文档,可以帮助你更好地理解如何在bash中使用命令分组。请点击上方链接查看详细内容。

在嵌套复合命令中,分号;是不必要的。例如:{ if true; then echo hello; fi }for i in {1..3}; do if true; then echo "$i"; fi done{ for i in {1..3}; do :; done },与需要分号;{ echo hello; }for i in {1..3}; do echo "$i"; done 相比。 - Yoory N.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接