Thursday, October 1, 2009

Semicolon (;) and double semicolon (;;) in shell script

- Semicolon in shell script often called command separator. In shell script each separate command need to be placed in each separate line. However, if we want to put two or more separate commands into one line then between them we need to place semicolon (;).
Following is a script which will explain the usage of semicolon. If there file exist then script delete the file and if file does not exist then it simply create the file.

$ cat >semicolon_test.sh
echo first command; echo second command
if [ -f newfile ]; then
echo "file exists"; rm newfile
else
echo "File not exists"; touch newfile
fi; echo "Script is done."

$ sh semicolon_test.sh
first command
second command
File not exists
Script is done.

$ ls
newfile semicolon_test.sh

$ sh semicolon_test.sh
first command
second command
file exists
Script is done.

$ ls
semicolon_test.sh


- Note that sometimes while using semicolon we need to escape semicolon. An example is,

find $PROCESSED_DIR -type f -mtime +30 -exec rm {} \;

The '\' ensures that the ';' is interpreted literally, as end of command.
Combination of "\;" at the end tells "find" where the end of the -exec command is. It can't just be the end of the line because the find command syntax allows further tests and actions after the -exec and it can't be just ; because the shell would see it as the end of a shell command and remove it. The \ "escapes" it from being seen by the shell as the end of a shell command.

- Double semicolon (;;) is used as a terminator of case option which is exampled in the topic http://arjudba.blogspot.com/2009/04/case-statement-in-shell-script.html.

- Double semicolon + ampersand (;;&, ;&) is used as terminators in a case option in version 4+ of Bash.

Related Documents

No comments:

Post a Comment