Writing shell scripts Flashcards
What are shell scripts?
In the simplest terms, a shell script is a file containing a series of commands. The shell reads this file and carries out the commands as though they have been entered directly on the command line.
The shell is somewhat unique, in that it is both a powerful command line interface to the system and a scripting language interpreter. As we will see, most of the things that can be done on the command line can be done in scripts, and most of the things that can be done in scripts can be done on the command line.
To successfully write a shell script, you have to do three things:
- Write a script
- Give the shell permission to execute it
- Put it somewhere the shell can find it
Writing a script
A shell script is a file that contains ASCII text. To create a shell script, you use a text editor. A text editor is a program, like a word processor, that reads and writes ASCII text files. There are many, many text editors available for your Linux system, both for the command line environment and the GUI environment.
Name/Description/Interface
vi, vim
The granddaddy of Unix text editors, vi, is infamous for its difficult, non-intuitive command structure. On the bright side, vi is powerful, lightweight, and fast. Learning vi is a Unix rite of passage, since it is universally available on Unix-like systems. On most Linux distributions, an enhanced version of the traditional vi editor called vim is used.
command line
Emacs
The true giant in the world of text editors is Emacs by Richard Stallman. Emacs contains (or can be made to contain) every feature ever conceived for a text editor. It should be noted that vi and Emacs fans fight bitter religious wars over which is better.
command line
nano
nano is a free clone of the text editor supplied with the pine email program. nano is very easy to use but is very short on features. I recommend nano for first-time users who need a command line editor.
command line
gedit
gedit is the editor supplied with the Gnome desktop environment.
graphical
kwrite
kwrite is the “advanced editor” supplied with KDE. It has syntax highlighting, a helpful feature for programmers and script writers.
graphical
chmod 755
give you read, write, and execute permission. Everybody else will get only read and execute permission. If you want your script to be private (i.e., only you can read and execute), use “700” instead.
!/bin/bash
The first line of the script is important. This is a special clue, called a shebang, given to the shell indicating what program is used to interpret the script. In this case, it is /bin/bash. Other scripting languages such as Perl, awk, tcl, Tk, and python also use this mechanism.
Paths
When you type in the name of a command, the system does not search the entire computer to find where the program is located. That would take a long time. You have noticed that you don’t usually have to specify a complete path name to the program you want to run, the shell just seems to know.
Well, you are right. The shell does know. Here’s how: the shell maintains a list of directories where executable files (programs) are kept, and only searches the directories in that list. If it does not find the program after searching each directory in the list, it will issue the famous command not found error message.
This list of directories is called your path.
How to view the list of directories (your path)?
echo $PATH
This will return a colon separated list of directories that will be searched if a specific path name is not given when a command is attempted.
Add directories to your path
export PATH=$PATH:directory
(where directory is the name of the directory you want to add)
A better way would be to edit your .bash_profile or .profile file (depending on your distribution) to include the above command. That way, it would be done automatically every time you log in.
Most Linux distributions encourage a practice in which each user has a specific directory for the programs he/she personally uses. This directory is called bin and is a subdirectory of your home directory.
Environment
During your session, the system is holding a number of facts about the world in its memory. This information is called the environment. The environment contains such things as your path, your user name, the name of the file where your mail is delivered, and much more. You can see a complete list of what is in your environment with the set command.
Two types of commands are often contained in the environment. They are aliases and shell functions.
How is the environment established?
When you log on to the system, the bash program starts, and reads a series of configuration scripts called startup files. These define the default environment shared by all users. This is followed by more startup files in your home directory that define your personal environment. The exact sequence depends on the type of shell session being started. There are two kinds: a login shell session and a non-login shell session. A login shell session is one in which we are prompted for our user name and password; when we start a virtual console session, for example. A non-login shell session typically occurs when we launch a terminal session in the GUI.
Aliases
An alias is an easy way to create a new command which acts as an abbreviation for a longer one. It has the following syntax:
alias name=value
where name is the name of the new command and value is the text to be executed whenever name is entered on the command line.
Let’s create an alias called “l” and make it an abbreviation for the command “ls -l”. Make sure you are in your home directory. Using your favorite text editor, open the file .bashrc and add this line to the end of the file:
alias l=’ls -l’
It’s just another shell builtin
You can create your aliases directly at the command prompt; however they will only remain in effect during your current shell session.
Another example:
alias today=’date +”%A, %B %-d, %Y”’
Shell functions
Aliases are good for very simple commands, but if you want to create something more complex, you should try shell functions . Shell functions can be thought of as “scripts within scripts” or little sub-scripts.
Example: today() { echo -n "Today's date is: " date +"%A, %B %-d, %Y" }
Believe it or not, () is a shell builtin too, and as with alias, you can enter shell functions directly at the command prompt.
However, again like alias, shell functions defined directly on the command line only last as long as the current shell session.
Here script
!/bin/bash
A here script (also sometimes called a here document) is an additional form of I/O redirection. It provides a way to include content that will be given to the standard input of a command. In the case of the script below, the standard input of the cat command was given a stream of text from our script.
Since many types of markup used in html incorporate quotation marks themselves, it makes using a quoted string a little awkward. A quoted string can be used but each embedded quotation mark will need to be escaped with a backslash character.
sysinfo_page - A script to produce an HTML file
cat «_space;EOF
The title of your page Your page content goes here.
EOF
A here script is constructed like this:
command «_space;token
content to be used as command’s standard input
token
The token can be any string of characters. I use “EOF” (EOF is short for “End Of File”) because it is traditional, but you can use anything, as long as it does not conflict with a bash reserved word. The token that ends the here script must exactly match the one that starts it, or else the remainder of your script will be interpreted as more standard input to the command.
One more trick:
Changing the the “<
My System Information <h1>My System Information</h1>
Variables
Variables are areas of memory that can be used to store information and are referred to by a name. In the case of our script, we created a variable called “title” and placed the phrase “My System Information” into memory. Inside the here script that contains our HTML, we use “$title” to tell the shell to perform parameter expansion and replace the name of the variable with the variable’s contents.
Here's the improved script: #!/bin/bash
sysinfo_page - A script to produce an HTML file
title=”My System Information”
cat <
$title <h1>$title</h1>
How to create a variable
To create a variable, put a line in your script that contains the name of the variable followed immediately by an equal sign (“=”). No spaces are allowed. After the equal sign, assign the information you wish to store.
Rules for variable names
- Names must start with a letter.
- A name must not contain embedded spaces. Use underscores instead.
- You cannot use punctuation marks.
Environment Variables
!/bin/bash
When you start your shell session, some variables are already set by the startup file we looked at earlier. To see all the variables that are in your environment, use the printenv command. One variable in your environment contains the host name for your system. We will add this variable to our script like so:
sysinfo_page - A script to produce an HTML file
title=”System Information for”
cat <
$title $HOSTNAME <h1>$title $HOSTNAME</h1>
Executing a command in a script
$(some_command)
Assigning results of a command to a variable
right_now=$(date +”%x %r %Z”)
You can even nest the variables (place one inside another), like this:
right_now=$(date +”%x %r %Z”)
time_stamp=”Updated on $right_now by $USER”
Constants
As the name variable suggests, the content of a variable is subject to change. This means that it is expected that during the execution of your script, a variable may have its content modified by something you do.
On the other hand, there may be values that, once set, should never be changed. These are called constants. I bring this up because it is a common idea in programming. Most programming languages have special facilities to support values that are not allowed to change. Bash also has these facilities but, to be honest, I never see it used. Instead, if a value is intended to be a constant, it is given an uppercase name to remind the programmer that it should be considered a constant even if it’s not being enforced.
Environment variables are usually considered constants since they are rarely changed. Like constants, environment variables are given uppercase names by convention. In the scripts that follow, I will use this convention - uppercase names for constants and lowercase names for variables.
Shell functions
show_uptime()
{
}
Important points:
First, they must appear before you attempt to use them. Second, the function body (the portions of the function between the { and } characters) must contain at least one valid command. As written, the script will not execute without error, because the function bodies are empty. The simple way to fix this is to place a return statement in each function body. After you do this, our script will execute successfully again.
Stubbing
When you are developing a program, it is is often a good practice to add a small amount of code, run the script, add some more code, run the script, and so on. This way, if you introduce a mistake into your code, it will be easier to find and correct.
As you add functions to your script, you can also use a technique called stubbing to help watch the logic of your script develop. Stubbing works like this: imagine that we are going to create a function called “system_info” but we haven’t figured out all of the details of its code yet. Rather than hold up the development of the script until we are finished with system_info, we just add an echo command like this:
system_info() { # Temporary function stub echo "function system_info" }
The reason we use an echo command is so we get some feedback from the script to indicate that the functions are being executed.
command that outputs several interesting facts about the system, including the length of time the system has been “up” (running) since its last re-boot, the number of users and recent system load
uptime
command to provide a summary of the space used by all of the mounted file systems
df