Simple scripts

A shell script is a text file containing shell commands. When such a file is used, Bash reads and executes commands from the file, then exits. If the first line of a script begins with the two characters '#!', the remainder of the line specifies an interpreter for the program. You can specify Bash, or some other interpreter and write the rest of the script file in that language. The characters '#!' are traditionally called the hash and the bang, or the shortened form "shebang". Bash scripts often begin with #! /bin/bash
(assuming that Bash has been installed in /bin), since this ensures that Bash will be used to interpret the script.

It helps to become comfortable using a text editor before writing shell scripts, since you will need to create files in plain text. UNIX has many text editors. The vi editor is one of the most common text editors on Unix. The traditional vi is extremely powerful but has a steep learning curve. nano is a small and friendly text editor. The usual way to invoke nano is nano file. Type nano sample.sh to create sample.sh file.

$ nano sample.sh

You simply type with your keyboard, using the arrow keys to move around and the delete or backspace keys to delete text. At the bottom of the screen you can see some commands available to you. Start typing a simple shell script while inside nano.

#! /bin/bash
echo a b c

Note that the bottom-left option is ^X Exit which means "press Ctrl and X key together to exit". You can exit the program without saving by pressing the N key, or save first by pressing Y to save. The default is to save the file with the current file name. You can press the Enter key to save and exit. A shell script may be made executable by using the chmod command.

$ chmod +x ./sample.sh

Running a script can be done either by passing it as an argument

$ bash sample.sh

or by running it directly.

$ ./sample.sh

Variables are a key part of any programming language. A very simple use of variables is to assign some text to a variable. To assign to a variable, just use the name of the variable. To access the contents of the variable, prefix it with a dollar sign.

#! /bin/bash
echo linux is $animal

Loops allow code to be executed repeatedly. They can be useful in numerous situations, such as when you want to run the same commands, or repeat some action numerous times. for loops are used when you have a finite collection over which you want to iterate.

#! /bin/bash
for names in server1 server2 server3; do
echo $names

After a program runs, it returns an exit code which is an integer between 0 and 255. An exit code of 0 means "everything is OK". Exit codes greater than 0 mean some kind of error happened, which is specific to the program.