September 2010
M T W T F S S
« Apr    
 12345
6789101112
13141516171819
20212223242526
27282930  

The Essential of Shell scripts

In Linux world, shell script is a powerful language, maybe it’s not easy, but it’s practical for use.
I have read a lot of scripts in the past, but when asked to write a snippet of script, I usually need to query other’s code for reference.
But today suddenly I find shell script is quite practical and Linux-friendly. Below are some clarifies and examples.
The familiar form for flow control is “if”, how to use it? It’s not as simple as in java or in c/c++.

# First form
if condition
then
  commands
fi

Example 1:
if gcc demo.c –o demo
then
 echo "sucess"
fi

Firstly, the condition is also a command, the return value indicate its success or failure, linux treat exit value 0 as success/true, other values as failure/false.
So here it contradicts with normal treatment with 0/1 as true/false.

Second, as the condition is a command, a semicolon can follow the condition and followed by another command or statement. or to say, there is another form.
if gcc demo.c –o demo; then echo "sucess"; fi

Some more forms about if list below:

# Second form
if condition ; then
commands
else
commands
fi

# Third form
if condition ; then
commands
elif condition
commands
fi

Please compare the three formats below:

Example 2:
if [ -f .bash_profile ]; then
echo “You have a .bash_profile. Things are fine.”
else
echo “Yikes! You have no .bash_profile!”
fi
# Alternate form
if [ -f .bash_profile ]
then
echo “You have a .bash_profile. Things are fine.”
else
echo “Yikes! You have no .bash_profile!”
fi
# Another alternate form
if [ -f .bash_profile ]
then echo “You have a .bash_profile. Things are fine.”
else echo “Yikes! You have no .bash_profile!”
fi

1 comment to The Essential of Shell scripts

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>