Richard Rublev Richard Rublev - 4 months ago 14
Linux Question

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

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

#!/bin/bash

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

mycd

./p2


p2 is executable

But

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


Why?

Answer

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.