≡ Menu

Bash Scripting Introduction Tutorial with 5 Practical Examples

Similar to our on-going Unix Sed and Unix Awk series, we will be posting several articles on Bash scripting, which will cover all the bash scripting techniques with practical examples.

Shell is a program, which interprets user commands. The commands are either directly entered by the user or read from a file called the shell script.

Shell is called as an interactive shell, when it reads the input from the user directly.

Shell is called as an non-interactive shell, when it reads commands from a file and executes it. In this case, shell reads each line of a script file from the top to the bottom, and execute each command as if it has been typed directly by the user.

Print the value of built in shell variable $-, to know whether the shell is an interactive or non-interactive.

# echo $-
himBH

Note: $- variable contains an “i” when the shell is interactive.

Unix has variety of Shells. Bourne shell (sh), Bourne again shell (bash), C shell (csh), Korn shell (ksh), Tenex C shell (tcsh). Use the which or whereis unix commands to find out where a specific shell is located as shown below.

# which bash
/bin/bash

# whereis bash
bash: /bin/bash /usr/share/man/man1/bash.1.gz

You can switch between the shells, by typing the shell name. For example, type csh to switch to C shell.

Writing and execution of shell script

Example 1. Hello World Bash Script

  1. Create a script by typing the following two lines into a file using your favourite editor.
  2. $ cat helloworld.sh
    #!/bin/bash
    echo Hello World
  3. You can choose any name for the file. File name should not be same as any of the Unix built-in commands.
  4. Script always starts with the two character ‘#!’ which is called as she-bang. This is to indicate that the file is a script, and should be executed using the interpreter (/bin/bash) specified by the rest of the first line in the file.
  5. Execute the script as shown below. If you have any issues executing a shell script, refer to shell script execution tutorial
  6. $ bash helloworld.sh
    Hello World
  7. When you execute the command “bash helloworld.sh”, it starts the non-interactive shell and passes the filename as an argument to it.
  8. The first line tells the operating system which shell to spawn to execute the script.
  9. In the above example, bash interpreter which interprets the script and executes the commands one by one from top to bottom.
  10. You can even execute the script, with out leading “bash” by:
    • Change the permission on the script to allow you(User) to execute it, using the command “chmod u+x helloworld.sh”.
    • Directory containing the script should be included in the PATH environment variable. If not included, you can execute the script by specifying the absolute path of the script.
  11. echo is a command which simply outputs the argument we give to it. It is also used to print the value of the variable.

Bash-Startup files

As we discussed earlier in our execution sequence for .bash_profile and related files article, when the bash is invoked as an interactive shell, it first reads and executes commands from /etc/profile. If /etc/profile doesn’t exist, it reads and executes the commands from ~/.bash_profile, ~/.bash_login and ~/.profile in the given order. The –noprofile option may be used when the shell is started to inhibit this behavior.

Typically your bash_profile executes ~/.bashrc. If you like, you can show a welcome message. This only runs when you first log in. You can export the variables whatever you want, and you can set the aliases which will be running and available once you opened the shell. When a login shell exits, Bash reads and executes commands from the file ~/.bash_logout.

Example 2. Print a welcome message when you login

Type the following contents in your bash_profile file. If the file doesn’t exist, create a file with the below content.

$ cat ~/.bash_profile
hname=`hostname`
echo "Welcome on $hname."

When you login to an interactive shell, you will see the welcome messages as shown below.

login as: root
root@dev-db's password:
Welcome on dev-db

Example 3. Print system related information

When you login to an interactive shell, you can show the name of the kernel installed in the server, bash version, uptime and time in the server.

$cat ~/.bash_profile
hname=`hostname`
echo "Welcome on $hname."

echo -e "Kernel Details: " `uname -smr`
echo -e "`bash --version`"
echo -ne "Uptime: "; uptime
echo -ne "Server time : "; date

When you launch an interactive shell, it prints the message as shown below.

login as: root
root@dev-db's password:
Welcome on dev-db

Kernel Information:  Linux 2.6.18-128 x86_64
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
Uptime:  11:24:01 up 21 days, 13:15,  3 users,  load average: 0.08, 0.18, 0.11
Server time : Tue Feb 22 11:24:01 CET 2010

Example 4. Print the last login details

If multiple users are using the same machine with same login, then details like the machine from which the last login happened, and time at which they logged in, would be the most useful details. This example prints the last login details during the starting of an interactive shell.

$ cat ~/.bash_profile
hname=`hostname`
echo "Welcome on $hname."

echo -e "Kernel Details: " `uname -smr`
echo -e "`bash --version`"
echo -ne "Uptime: "; uptime
echo -ne "Server time : "; date

lastlog | grep "root" | awk {'print "Last login from : "$3

print "Last Login Date & Time: ",$4,$5,$6,$7,$8,$9;}'
During start up, you will get the message as shown below.

login as: root
root@dev-db's password:
Welcome on dev-db

Kernel Information:  Linux 2.6.18-128 x86_64
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
Uptime:  11:24:01 up 21 days, 13:15,  3 users,  load average: 0.08, 0.18, 0.11
Server time : Tue Feb 22 11:24:01 CET 2010

Last login from : sasikala-laptop

Last Login Date & Time: Tue Feb 22 11:24:01 +0100 2010

Example 5. Export variables and set aliases during start-up

The most common commands you will use in your .bashrc and .bash_profile files are the export and alias command.

An alias is simply substituting one piece of text for another. When you run an alias, it simply replaces what you typed with what the alias is equal to. For example, if you want to set an alias for ls command to list the files/folders with the colors, do the following:

alias ls 'ls --color=tty'

If you add this command to one of the start-up files, you can execute ls command, where it will be automatically replaced with the ls –color=tty command.

Export command is used to set an environment variable. Various environment variables are used by the system, or other applications. They simply are a way of setting parameters that any application/script can read. If you set a variable without the export command, that variable only exists for that particular process.

In the example below, it is exporting the environment variable HISTSIZE. The line which is starting with # is a comment line.

$ cat /etc/profile
alias ls 'ls --color=tty'

# Setup some environment variables.
export HISTSIZE=1000

PATH=$PATH:$HOME/bin:/usr/bin:/bin/usr:/sbin/etc

export PATH

export SVN_SH=${SVN_RSH-ssh}

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 8 comments… add one }

  • Chris F.A. Johnson March 3, 2010, 11:09 am

    There is no good reason to use an external command (which) to find the location of a shell or any other executable file. Bash, like all Bourne-type shells, has the builtin command ‘type’.

    If the command is a function or an alias, ‘which’ will not tell you that; ‘type’ will.

  • Chris F.A. Johnson March 3, 2010, 11:14 am

    Re: echo -e “Kernel Details: ” `uname -smr`

    Command substitution is slow and, in this case, unnecessary.

    Using ‘echo’ (which I don’t recommend) you could do:

    echo -n “Kernel Details: ”
    uname -smr

    I rarely use echo because of portability problems; printf is universal:

    printf “Kernel Details: ”
    uname -smr

  • vasiauvi March 6, 2010, 3:41 am

    Thanks for this tutorial and wait the next one about bash scripting.

    P.S. It would be nice if there where on your site option to save this kind of tutorials in pdf mode…I know there are addons for this but it’s an idea to implement directly in the site!

    have a nice weekend!

  • Chris F.A. Johnson March 6, 2010, 4:39 pm

    man bash:

    For almost every purpose, aliases are superseded by shell functions.

  • dfsdfsd March 7, 2010, 6:38 am

    Good post!

  • Michael Fread April 7, 2014, 12:07 pm

    This is a little sparse on content to qualify as a bash tutorial. You aren’t going to be able to do much without at least having conditionals and loops.

  • Chris F.A. Johnson April 9, 2014, 4:03 pm

    Michael, this is just an introduction, and they “will be posting several articles on Bash scripting”.

  • Logan Bender June 19, 2014, 9:58 am

    It is unclear in example 1. step 1 that the first line of the example script “$ cat helloworld.sh ” is actually the filename of the script and is not to be included in the actual body of the script. As an introduction, such distinctions should be made.

Leave a Comment