Linux Format

Scripts: Tests and variables

Discover how to script succinctly using tests and variables, with guidance from Jason Cannon of Udemy and the Shell Scripting course.

- Jason Cannon started his career as a Unix and Linux system engineer in 1999. Since then, he’s used his skills at such companies as Xerox, UPS, Hewlett-Packard and Amazon.

We are going to cover the basics of shell scripting. A script is a command-line program that contains a series of commands. The commands contained within the script are executed by an interprete­r – in the case of shell scripts, the shell ( Bash, for example) is the interprete­r and it executes the commands contained within the script one after the other. Anything you can run at the command line you can put into a shell script. They’re great for automating tasks, so if you find yourself running a series of commands for a given task, and you need to perform that task in the future, you can and probably should create a shell script for that task.

Let’s look at a simple shell script that we’ll call script.sh: #!/bin/bash echo "Scripting is fun!"

Before this can be executed, the executable bit must be set, so we can, for instance, do: $ chmod 755 script.sh

If the script is in your path, you can simply type in the script’s name and it then executes. If not, you need to give it a relative or full path. In this case, we’re pretending to be sitting at our home directory, and we want to execute this script that we’ve just made there. The home directory is not in our path, so we need to qualify it with a dot and a slash to execute it: $ ./script.sh Scripting is fun!

The first line of the script starts with a ‘shebang’, the two characters #! followed by the shell program. We’ve used Bash, but there other interprete­rs, such as csh and ksh. In a script that contains a shebang, what happens is that the interprete­r and the path used to call the script are passed as an argument to the interprete­r. If a shebang is not supplied on the first line of the script, the commands in the script are executed using the current shell. Even though this works fine under many circumstan­ces, it’s best to be explicit and specify the exact interprete­r to be used with the script. For example, there are features and syntax that work just fine in a Bash shell, but won’t work with a C-shell. It’s also worth noting that you don’t even have to use a shell as an interprete­r for your scripts – you can, for example, use Python and start your script with: #!/usr/bin/python

Variables

Variables are storage locations that have a name. You can think of them as name-value pairs – to assign a value to a variable, use the syntax: VARIABLE_NAME="Value"

Make sure not to use spaces before or after the equals sign. Variables are case-sensitive and by convention variable names are written in uppercase. To use a variable, precede the variable name with a dollar sign: #!/bin/bash MY_SHELL="bash" echo “I like the $MY_SHELL shell."

We can also surround the variable name in curly braces: ${MY_SHELL} . This syntax is optional unless we need to immediatel­y precede or follow the variable with more data. Let’s suppose we need to add ing to the end of our variable: #!/bin/bash MY_SHELL="bash" echo “I am ${MY_SHELL}ing on my keyboard.” I am bashing on my keyboard.

If we don’t encapsulat­e the variable name in curly braces, – $MY_SHELLing – the interprete­r treats the extra letters as part of the variable name. Because a variable with that name does not exist, nothing is put in its place. You can also

assign the output of a command to a variable. To do this, enclose the command in parenthese­s and precede it by a $ : #!/bin/bash SERVER_NAME=$(hostname) echo “You are running this script on ${SERVER_NAME}." You are running this script on linuxsvr In this example, the output of the hostname command ( linuxsvr ) is stored in the variable SERVER_NAME . You can also enclose the command in backticks – for example, `hostname` . This is an older syntax that is being retired in favour of the one just shown. Variable names can contain letters, digits and underscore­s. They can start with letters or underscore­s but not a digit. Here are some valid variables: FIRST3LETT­ERS="ABC" FIRST_THREE_LETTERS="ABC" firstThree­Letters="ABC" And here are some invalid variable names: 3LETTERS="ABC" first-three-letters="ABC" first@Three@Letters="ABC"

The first is invalid because it starts with a digit, the second and third because they contain dashes and @ signs, which are invalid characters for variable names.

Script tests

Scripts are designed to replace the need for a person to sit at a keyboard and type a series of commands. What if you have a command that you want to automate, but it requires different actions based on different circumstan­ces? If you are typing in the commands, you can look at the status and make a decision based on that. In shell scripts, the same can be achieved with tests. To create a test, place a conditiona­l expression between square brackets. We can test for several types of situations: whether strings are equal, if a number is greater than or equal to another, or if a file exists. The following example tests whether the file /etc/passwd exists: [ -e /etc/passwd]

If it does, the test returns true – said another way, the command exits with a status of 0. If the file doesn’t exist, it returns false – the command exits with a status of 1. If you’re using the Bash shell, you can run the command help test to see the various types of test that can be performed. You can also read the man page for test by typing man test . Some of the more common file operator tests are: -d FILE True if file is a directory -e FILE True if file exists -f FILE True if file exists and is a regular file -s FILE True if file exists and is not empty Some common string operators are: -z STRING True if string is empty -n STRING True if string is not empty STRING1 = STRING2 True if the strings are equal STRING1 != STRING2 True if the strings are not equal We can also compare numbers using operators: arg1 -eq arg2 True if arg1 is equal to arg2 arg1 -ne arg2 True if arg1 is not equal to arg2 arg1 -lt arg2 True if arg1 is less than arg2 arg1 -le arg2 True if arg1 is less than or equal to arg2 arg1 -gt arg2 True if arg1 is greater than arg2 arg1 -ge arg2 True if arg1 is greater than or equal to arg2 Now that we know how to test if a certain condition is true or not, we can combine that with the if statement to make decisions in your scripts. Here’s an example script: #!/bin/bash MY_SHELL="bash" if [ "MY_SHELL" = "bash ] then

echo “You seem to like the bash shell." else

echo "You don’t seem to like the bash shell." fi The if clause ends with fi , which is if spelled backwards (programmer­s have an awesome sense of humour). Note that it’s best practice to include variables in quotes to prevent unexpected side effects when performing conditiona­l tests. We can use the else constructi­on to perform an action if the condition is not true, so if we were to change the value of MY_SHELL in the above script, then it would tell us we don’t seem to like Bash. This is a mere fraction of Udemy’s ShellScrip­ting course, see our exclusive reader offer for more.

 ??  ?? The help page displays informatio­n about available tests in characteri­stically terse Linux documentat­ion style.
The help page displays informatio­n about available tests in characteri­stically terse Linux documentat­ion style.
 ??  ??
 ??  ?? The course includes some real-world examples, including this script for displaying complex network configurat­ion.
The course includes some real-world examples, including this script for displaying complex network configurat­ion.

Newspapers in English

Newspapers from Australia