Richard Rublev Richard Rublev - 2 months ago 8x
Linux Question

"syntax near unexpected token `{cd'" defining shell function

Following advices I got from my previous post,I wrote a bash script


{cd /home/milenko/data;}



p2 is executable


milenko@milenko-HP-Compaq-6830s:~$ bash line 4: syntax error near unexpected token `{cd' line 4: `{cd /home/milenko/data;}'



Shell syntax (not just bash, but in POSIX sh) is built around units called "words". { only has its syntactic meaning when parsed as its own word -- meaning it needs to be surrounded by whitespace (a category which includes newlines).

The conventional way to write this would be:

mycd() {
  cd /home/milenko/data

...or, if you wanted to minimize newlines:

mycd() { cd /home/milenko/data; }

You could remove the space between the final ; and closing } (since ;, when found outside quotes and not escaped, ends any word which was preceding it), but this would be considered ugly:

mycd() { cd /home/milenko/data;} # leaving out the last space is legal, but please don't.