-1

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?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Richard Rublev
  • 7,718
  • 16
  • 77
  • 121

1 Answers1

1

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.
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441