Scripting Without Programming: Bash
It is common for systems administrators to write scripts in order to perform repeated tasks faster or enable tasks to be completed when the administrator is not logged into the server by assigning the script to a scheduler such as cron. A script can also be for a one-off task that can take a long time to complete. These scripts will normally be written in whichever language that the administrator is proficient in. If you think that scripting could help make the administration of your server easier, but you don’t know any programming languages, there is a solution.
Bash, or the Bourne-Again SHell to give it its full name, is the most commonly used terminal shell on Linux. Normally you interact with Bash by typing commands individually at the command prompt or chaining them together with pipes. Sometimes you may use Bash’s variable substitution at the command line, but this feature comes into its own when scripting. Along with variables, Bash includes other common programming features such as conditional execution (decision making) and loops alongside the ability to perform arithmetic, meaning that it’s possible to write Bash scripts that can perform some quite complex tasks.
In general, programming languages consist of lines of instructions that either control the program’s flow or perform individual tasks. The parts that perform the tasks are usually called functions. Whilst the instructions to control program flow tend to be fairly common and recognizable between languages, the functions tend to be specific to the language. As Bash itself isn’t a programming language, it doesn’t have pre-built functions to perform tasks: for that we use commands. These are the same commands you’d normally be entering at the command prompt whilst using the Linux terminal on a day-to-day basis. This makes the learning curve for writing scripts in Bash fairly low as you should already be familiar with many commands.
How To Start A Bash Script
The standard way to start a Bash script is with a shebang or hashbang. This is a line that starts with the hash symbol and an exclamation mark (#!), followed by the path to the interpreter that is meant to run it. In the case of a Bash script the shebang line would look like:
This is needed if you wish to allow users to run the script as though it were a regular executable file. Without it the user would need to call the bash command and pass the script as an argument:
With the shebang in place, the script can simply be called by itself.
It could also be placed within a directory contained within the user’s normal PATH environment variable such as /usr/bin allowing them to call the script without needing to know about the nature of the script.
That completes this brief introduction. In the next part, we’ll be looking at making our first simple bash scripts, and how to use them.