Learning to script on Linux using bash

Here are some basic skills to get started with bash, one of the best shells for preparing and using scripts on Linux.

rules rulebook letters compliance regulation by alex ishchenko getty
Alex Ishchenko / Getty

Scripting in Linux--putting commands into a file so you can run them as a group—is a lot easier than running them from the command line because you don't have to figure out the process over and over again. Aliases can also be used to repeat commands easily, but are really only used for individual commands that are complex or difficult to remember.

As you will see in the examples below, the bash shell provides plenty of commands for testing, looping, creating functions, and annotating your scripts.

The best way to start learning to script is to come up with some problems and then try to script the solutions. You can get ready by learning and practicing some basic scripting techniques.

Give scripts meaningful names

Scripts should have names that describe what they do. For example, a good name for the following script might be "square" because it provides the square of whatever number is entered on the command line.

$ cat square
#!/bin/bash

number=$1
echo $number^2 | bc

Running it ...

$ square 12
144

Assign permissions based on who can run the scripts

For scripts to run, they need execute permission. If you assign 750, you and anyone in your primary group can run them, but only you can edit them.

$ chmod 750 square

If a script doesn't have execute permission, it can still be run by "sourcing" it. This means using a command like that shown below to read and execute the file contents line by line.

$ . square 12
144

Set up and check variables

The square script shown above uses the number variable to capture the value provided when the script is run and would result in an error if none is provided.

$ square
(standard_in) 1: syntax error

You could avoid that error possibility by verifying that an argument is provided to the script. Note: This check doesn't test whether the argument provided is numeric.

#!/bin/bash

if [ $# == 1 ]; then
  number=$1
  echo $number^2 | bc
fi

In this case, the script will not end in an error, but will simply do nothing if no value is entered,

Prompt for arguments

Another way to handle the problem shown in the square script above is to prompt for the values needed or prompt for the values only if none were provided.

#!/bin/bash

if [ $# == 1 ]; then
  number=$1
else
  echo -n "number to square: "
  read number
fi

echo $number^2 | bc

Use if commands to run tests

As shown in the example above, you can use if commands to run tests to be sure required arguments are provided. if tests can be used to test for many things. In the script below, we're looking to see if the script is being run on a Friday.

#!/bin/bash

if [ `date +%A` = "Friday" ]; then
  echo Send weekly report
else
  echo Add daily updates to weekly report
fi

Use looping commands like for and while

Loops in scripts can be incredibly useful because they allow you to repeat commands as many times as needed or until you kill the script. Here are some simple examples of using the for command. The first runs through the alphabet pausing for 10 seconds between each letter. The second runs through the home directories on the system and reports how much disk space each is using. It should be run by sudo since individual users will not be able to access other home directories.

First script:

#!/bin/bash

for x in {a..z}
do
    echo $x
    sleep 10
done

Second script:

#!/bin/bash

for user in `ls /home`
do
    du -skh /home/$user
done

While commands run as long as some condition continues to be true. Using "while true" means a loop will continue until it runs into an error.

#!/bin/bash

while true
do
   who
   sleep 5
done

The script above runs until it is stopped with a ^c. The one below stops when it has finished displaying each line in a file preceded by line numbers.

#!/bin/bash

echo -n "File> "
read file
n=0

while read line; do
  ((n++))
  echo "$n: $line"
done < $file

Add comments to scripts

Comments can make it a lot easier for people (even you) to understand or remember what a script is supposed to be doing. Consider adding comments that explain the script's function or clarify complex commands. Comments start with a #, but don't need to start at the beginning of a line.

#!/bin/bash
# calculate space used by home directories

for user in `ls /home`
do
    du -sk /home/$user		    # show size of each home directory
done

Verify commands have run successfully

You can easily verify that a command in a script has run successfully by checking the return code. In this example, the script uses that technique.

#!/bin/bash
# create or update a file

if [ $# == 1 ]; then    # one argument expected
  touch $1 2> /dev/null
else
exit 1 fi # report on whether the command was successful if [ $? -eq 0 ] # $? is return code for the touch command then echo "Successfully created file" else echo "Could not create file" fi

The script shown above tries to create or update a file with the touch command. If the touch command is unsuccessful because of a permissions problem, the return code ($?) will not equal 0, indicating a failure.

$ touchFile /etc/whatever
Could not create /etc/whatever

Send error output to /dev/null

In the touch command shown in the prior example, error output was sent to /dev/null to avoid having the error showing up on the screen. Instead, error codes of 1 or greater result in a message that explains that the file was not created and can be used to create "friendly" error messages if needed.

Create functions to be called when needed

Functions make it easy to repeat segments of the code in a script as often as needed. If you prepared a script that requires periodically creating a directory and then moving into it with cd, you might add a function like this and then call it by using a command like "newdir report" or "newdir backups".

newdir () {
    mkdir -p $1
    cd $1
}

You can set up and use functions on the command line, but they will not continue to exist after you log out.

$ test_function () { echo This is a function; }
$ test_function
This is a function

Wrap-Up

Once you get used to building them, creating scripts that will make your daily work easier can be both fun and profitable. Well written scripts can save you a lot of time and preserve the problem-solving techniques that you have developed.

Join the Network World communities on Facebook and LinkedIn to comment on topics that are top of mind.
Related:

Copyright © 2022 IDG Communications, Inc.