Yogesh Yogesh - 2 months ago 16
Bash Question

Why Shell script runs with dangling '}'?

I wrote this script to compile and run my C and java programs with a single command.

1 run(){
2 gcc -lm $1 && ( shift; ./a.out $* )
3 }
4
5 jrun(){
6 clas=`echo $1 | cut -d'.' -f1 `
7 javac $1 && { shift; java $clas $* }
8 }


But on running getting error.

# source t.sh
-bash: t.sh: line 9: syntax error: unexpected end of file


Script run successfully when I added
'}'
at the end.

Just realized that I used
{}
instead of
()
in
line 7
.

My question is why it run and work fine with a danging
'}'
?

Answer

You need a semicolon after the $* to separate the brace. As it is, it's simply interpreted as an argument to javac.

As an aside, you are probably looking for

run(){
   gcc -lm "$1" || return
   shift
   ./a.out "$@"
   }

jrun(){
   javac "$1" || return
   local clas=${1%.*}
   shift
   java "$clas" "$@"
 }

which fixes the many quoting issues, and avoids the slightly clumsy compound commands. The local declaration prevents the function from clobbering a global variable with the same name, but is a bashism.