Difference between revisions of "Shell scripting tutorial"

From Linuxintro
imported>ThorstenStaerk
imported>ThorstenStaerk
Line 33: Line 33:
 
Let's look at the following script:
 
Let's look at the following script:
 
  read name
 
  read name
  if [ $name = "Thorsten" ]; then echo "I know you"
+
  if [ $name = "Thorsten" ]; then echo "I know you"; fi
 
Instead of a semicolon you can write a line feed like this:
 
Instead of a semicolon you can write a line feed like this:
 
  read name
 
  read name
 
  if [ $name = "Thorsten" ]
 
  if [ $name = "Thorsten" ]
 
   then echo "I know you"
 
   then echo "I know you"
 +
fi
 
And instead of a line feed you can use a semicolon:
 
And instead of a line feed you can use a semicolon:
  read name; if [ $name = "Thorsten" ]; then echo "I know you"
+
  read name; if [ $name = "Thorsten" ]; then echo "I know you"; fi
 
If you want to insert a line feed where you do not need one, e.g. to make the code better readable, you must prepend it with a backslash:
 
If you want to insert a line feed where you do not need one, e.g. to make the code better readable, you must prepend it with a backslash:
 
  read \
 
  read \
Line 46: Line 47:
 
   then \
 
   then \
 
     echo "I know you"
 
     echo "I know you"
 +
fi
  
 
= calling commands =
 
= calling commands =

Revision as of 00:39, 2 January 2012

This is a tutorial for bash shell scripting.

Hello world

echo "hello world"
#!/bin/bash
echo "hello world"

input

echo "what is your name? "
read name
echo "hello $name"

common mistakes

Note that the variable is called $name, however the correct statement to read it is

read name

It is a common mistake to write

read $name

which means "read a string and store it into the variable whose name is stored in $name"

conditions

echo "what is your name? "
read name
if [ $name = "Thorsten" ]; then echo "I know you"; fi

common mistakes

Common mistakes are:

line feeds

Let's look at the following script:

read name
if [ $name = "Thorsten" ]; then echo "I know you"; fi

Instead of a semicolon you can write a line feed like this:

read name
if [ $name = "Thorsten" ]
  then echo "I know you"
fi

And instead of a line feed you can use a semicolon:

read name; if [ $name = "Thorsten" ]; then echo "I know you"; fi

If you want to insert a line feed where you do not need one, e.g. to make the code better readable, you must prepend it with a backslash:

read \
  name
if [ $name = "Thorsten" ]
  then \
    echo "I know you"
fi

calling commands

Calling commands in a bash script is as easy as it can be: You just write the command to be called, like this:

echo "Now calling a browser"
firefox
echo "Continuing with the script"

See also