Bash script programming basics with practical examples

(Last Updated On: April 2, 2021)

Bash Script introduction

HelloWorld!

The classic Hello World program consists of just two lines:

As with Python scripts, the first line indicates the location of the interpreter. The file should thus be processed by the program / bin / bash to output a character string. If you start the line with echo in the beginning and you save your editor in a text file, the result is initially just a text. To get out of it, to make an executable program, you need to Set the execute bit. You can then use the program in the form ./filename To run:


Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Another example

The following script is only one line longer, but already fulfills a useful one Task: It takes a photo with the Raspberry Pi camera and saves it under the Name /home/pi/Bilder/img-hh-mm.png. Here hh becomes through the hour and mm through replaced the minute. The date command determines this data. Calling date takes the form $ (…). That means that the result of date is in the string is installed. The script itself has the file name / home / pi / makephoto.

The following file /etc/cron.d/makephotos causes the script to automatically run all 10 minutes is called up. pi in the sixth column causes the script under the account pi is executed, not with root privileges. In general, you should try to use cron Only execute jobs in the root account if this is absolutely necessary.

The bash script in combination with the cron setting causes that during the 144 pictures can be recorded and saved in the first 24 hours. As a result older images are replaced by newer ones, so that they remain available for 24 hours. The space required for all images in the chosen Resolution of 1280×800 pixels is approx. 100MByte.



Elementary syntax rules

  • Shebang / Hashbang: The first line of the bash script is in the form #! / Bin / bash the location of the shell interpreter. Don’t use #! / Bin / sh here! So that your script is not executed by bash, but by the bash interpreter. This Program is optimized for higher speed, but not completely compatible with bash.
  • Comments: Comments are introduced with the # character and are sufficient to the end of the line.
  • Instructions: The general rule is: one instruction per line. With very long statements there is the possibility to use the character \ in the to continue next line. Conversely, you can use a few short commands by the sign; also specify separately within a line. In addition to internal bash commands such as cd, all of them can also be executed in Linux commands available at the terminal, i.e. from apt-get for package management to zip for creating ZIP archives. The latter command assumes that you have previously installed the package of the same name.
  • Character strings: Character strings can be either ‘abc’ or “abc” must be specified. But these forms are not equivalent! Strings in single apostrophes are always passed on unchanged. With strings however, bash tries to put it in double quotes replace the contained character strings in the form $ varname with their content.
  • Variables: Variables are usually preceded by a $ sign marked. A little unusual in this context, however, is that assignments to variables are made without the $ sign! So it’s called var = 3, but echo $ var. internally in bash, variables only save strings, d. i.e. there is no difference between var = 3 and var = ‘3’.

Call up commands

Many bash programs are nothing more than a series of Linux Commands to be executed. The call to external tools that is used in is a special case in almost all other programming languages, the Normal case and does not require any special functions: Every instruction that the bash not recognized as an internal command, leads to the call of the corresponding external Commands, bash searches for the command in all directories that are in the environment variable PATH are listed. If the bash does not find the command i.e. due to a typo or because the relevant command is not installed at all is an error occurs.


Table 1:Calling commands

syntax Importance
cmd run the command cmd
cmd \tblcol cmd in the background
cmd1; cmd2 first run cmd1, then cmd2
(cmd1; cmd2) Run cmd1 and cmd2 in the same shell
cmd1 & cmd2 Runs cmd2 only if cmd1 is successful.
cmd1 || cmd2 Only executes cmd2 if cmd1 returns an error.
cmd1 | cmd2 cmd2 processes the output from cmd1.
x=$(cmd) Saves the output of cmd in the variable x.
x=cmd as above

 

Since calling commands is so elementary for bash, it is not surprising that there are a number of syntactic variants for this (see Table1). Often should Process the command files to be called. The file name can have wildcards contain. cat * .txt shows all files with the ending .txt. Still The find command offers significantly more options for searching files.

Of course, for all commands that you call in a bash script, you can make use of the input and output diversion and so i.e. the results a command with> filename in a temporary file.

Branch into another script

You can call other bash scripts from your bash script simply by naming the Execute filename. For scripts from the current directory, you must not forget to put ./ in front: bash only searches for commands and scripts in the directories listed in PATH. The current directory whose location is simply by . abbreviated does not count for security reasons.

Instead of running another script like a standalone program, their codes with source file or through also integrate the file into the current script. However, this can easily lead to conflicts due to variables or Functions come or an unintentional end of the program through exit. Therefore it is usually safer to execute other scripts such as commands. The advantage of source is that the cost of resources is smaller. Especially no new instance of bash has to be started. This procedure is useful especially if you distribute your own code over several files and B. want to save all function definitions in a separate file.


bash or python?

Now which is the better language: bash or Python? You have already suspected: A clear answer is not to be expected here. As so often, it depends on what you want to aim. Bash is particularly suitable as a script language, if you can solve your tasks primarily with existing Linux commands. Bash is ideal for transferring data from one command to the next. But that also means: A basic requirement for using the bash is a good knowledge of the available commands that are used under Linux or especially on the Raspberry Pi.

Bash quickly reaches its limits when it comes to complex algorithms develop or manipulate large amounts of data in memory. The bash offers only very primitive syntactic possibilities for this and a comparative one low processing speed. The bash is particularly unsuitable for any kind of mathematical calculations: bash doesn’t even know floating point numbers! In practice, bash is often used as a system administration tool on Linux, e.g. to perform backups or to automate files, Upload a website or download it from the Internet. bash scripts are Compared to Python programs, they are often very short and often just exist from 10 or 20 lines.

Recommended For You

About the Author: Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

%d bloggers like this: