Bash for Beginners
BASH or the “Bourne-Again Shell” is the scripting language with which many Linux tasks are accomplished. It is an easy to use language and can be freely adapted and expanded which makes it extremely powerful.
It enables us to write our own commands, making systems automation (when the computer does the boring tasks) very easy. At HOSTAFRICA, we make extensive use of BASH to automate many of the day-to-day administration tasks.
In this short article, I will introduce some basic concepts. The BASH environment is the one you enter when you log in to your Linux server.
Bash Commands and humour
The bash command-set consists of any command available in Linux. Any software you install on Linux that has command line commands becomes available to use in BASH. A good example is PHP where you can call PHP scripts using bash. Perl commands and the whole C command forest is also available. On a minimal install Linux system, you have almost 4000 commands available. Most of us use only a few hundred. Many bash commands display Geek humour such as the commands dealing with displaying the contents of a file. Using tail gives us the last lines of a file while the head command gives you the first lines. To get the whole file content, use cat (comes between head and tail). The cat command is also an abbreviation for con-cat-enate as you can join the content of many files with it. Many tongue-in-cheek commands exist which are thus related i.e. less and more, if and fi and a few other.
Bash auto-complete
The Linux command line has one amazing feature (which windows has since copied in PowerShell) called “tab-completion”. This basically means that after typing 3 letters of a command or filename, you can press the TAB key and BASH will attempt to complete the command or filename. Many people interpret this as a sign of laziness and do not want to use this. Auto-Complete or Tab-Complete has nothing to do with laziness and EVERYTHING to do with ACCURACY as it ensures that the correct spelling is used for a command or filename. One also develops a feel for when you can or cannot use Tab-Complete as you use BASH.
Bash conventions
Certain conventions are good to know. Many commands can be modified with switches which are added to the basic command. Short Switches (single letter) are usually prefixed with a single dash (-) and long switched usually have a double-dash (–). Standard switches which work with many commands (but not all, and not always the same) are:
- -l (dash el) = long | gives more info on output
- -f ( dash eff) = full | gives more info on output
- -s (dash es) = short | gives a shortened or summarised output
- -v (dash vee) = verbose | gives more info as well, but more focussed on debugging. Can be doubled for more info ( -vv)
- -h (dash aitch) = help | gives a help summary
- –help | gives more help or help when -h does not work or is used for a different purpose
- -n (dash en) = numeric | gives more numeric, less text info
- -r (dash are) = reverse | reverse the order
- -q (dash queue) = quiet | give less or no output
Linux Directory basics and path navigation
Unlike windows where you have a c: drive, Linux does not declare drives but rather uses a flat directory root. This is called the root path and is indicated by a single forward slash (/). The actual root directory (/root) can be regarded as the home directory for the user “root“. This can be confusing at first but you will get used to it.
We can move around directories (as user root) with the “cd” command. To go to the home folder for all users, type:
cd /home
To move UP a directory level, use “cd ..” and to move to the system root, use “cd /“. To call a script in the current directory, use “./scriptname” – the single full-stop refers to the current directory. Just calling the script name will search the default PATH and not execute the local script unles it is in the PATH.
A directory listing is usually obtained with the “ls” command, although some Linux variants have added the DOS/Windows “dir” command.
You do not have to navigate to the home directory to get a listing as you can use the full path with a trailing slash i.e
ls /home/
Remember that Linux IS case sensitive, unlike DOS/Windows.
Script Editors
Before we start, we have to gain at least a basic knowledge of script editors. The most common and also most bothersome to use (for me at least) is an editor called vi or vim (vim stands for vi-more as it has added features).
- To create a new file called “helloworld.sh”, type “vi helloworld.sh” and press enter. This will open a blank editor window.
- To edit by INSERTION, type the letter “i“. You can now paste content. Be careful of pasting content copied from a windows environment as line-breaks/newlines are not always copied in a way that Linux understands and you may have either line breaks where you do not want them or no line breaks at all. Use Google to learn other vi / vim commands or learn to use a more modern editor such as nano or joe.
- To save the file, press the ESC key twice, the type colon (:) then wq (for write and quit) and press ENTER.
Script Structure
A bash script uses a Linux script structure. This starts with the “Interpreter declaration/path”. This is used by other scripting languages as well such as command line PHP, Perl and Ruby. I will demonstrate this with a short “Hello World” script below. Use a Linux cli editor such as vi/vim or nano or my favourite, joe (which you may have to install first) to create a file called helloworld.sh and copy and paste the content below into it.
#!/bin/bash # Filename: helloworld.sh # Author: eb 2017 # Comments are prefixed with a hash (#) and lines starting with #, with the exception of line 1 (#!) are ignored # Set a Variable. A variable can be any letter or word or alphanumeric (letter/number) combination. Try to avoid using # system/environmental variables of which you can get an idea by typing "set |more" . One which I used to get wrong on a # regular basis was declaring the "PATH to a file using the variable PATH, which is already used by BASH to declare # the path to all executables. Rather use FPATH (FilePath) as a variable. Let us set a variable and the display this to # the screen. ########################### GREETING="Hello World"; # this sets the variable $GREETING to contain "Hello World" # Always quote variable content unless it is a path # Display or "print" the variable content to the screen echo "$GREETING"; # The quotes here are not needed, but are better programming as quotes force variable # expansion (displaying the content, not the variable label) and also enable you to # join variable content with other variable or even text as follows. echo "...and I repeat, ${GREETING}!!!"; # Enclosing the variable in curly brackets ensures that any other # characters are not interpreted as per of the variable label. exit 0 ; #########################################################################################################################
To run the above variable, we can either call it with:
/bin/bash helloworld.sh
or we can make the file executable (which is where the “interpreter declaration” is used) by changing the mode of the file with
chmod +x helloworld.sh
Now the bash script can be run from the directory in which you saved it with:
./helloworld.sh
Unless you saved the script in the standard path for user scripts (/usr/local/sbin/) you will have to call the script with the full path to the script relative to the root.
Links
There are many excellent sources on the internet to learn about BASH.
Happy Hosting!