Roger Heathcote
Roger Heathcote

Reputation: 3555

What is causing this bash syntax error?

This command works fine on the command line...

if g++ -std=c++11 main.cpp ; then ./a.out; fi

But when I try to adding it to my .bashrc as a function it fails...

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

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

What am I doing wrong here?

Upvotes: 4

Views: 66

Answers (2)

glenn jackman
glenn jackman

Reputation: 247210

When using { braces } you need to have a newline or semi-colon before the close brace. For one-liners, that means you need a semi-colon

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

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

Upvotes: 3

chepner
chepner

Reputation: 532418

} isn't special; you need to explicitly terminate the preceding command with a ; if you put the function definition on one line.

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

Upvotes: 3

Related Questions