Loops, conditions, and functions in Bash Programming

(Last Updated On: September 9, 2021)

Loops, conditions, and functions:

loops conditions and functions:- this is a very detail article about loops, conditions and function in bash programming raspberry pi


if statement in bash programming:

The syntax for the if statement is as follows:

Any number of elif blocks are allowed. The following example tests whether the Script two parameters were passed. If not, you will get an error message. The program is exited with a return value ended not equal to 0 to indicate an error. Otherwise the content is displayed on the screen.

The return value of the last command is used as the criterion for branching then. The condition is fulfilled when this command delivers the return value 0. If then is specified in the same line and not in the next, then the command must end with a semicolon.




Wrong logic in bash programming:

Note that in bash the truth values ​​for true (0) and false (not equal to 0) are defined exactly the other way around than in most other programming languages! Commands that are properly terminated return 0.  A value not equal to 0 indicates an error. Depending on the error, some commands different error values.

In the example above, the condition was set using the bash command test. The operator -ne stands for not equal. test is Always used when two strings or numbers are compared should be used when testing whether a file exists, etc. The Command is described in more detail in the next section.

The above program could also be formulated differently: Instead of the test command a short form in square brackets can be used. They must be followed by a space after [and before]! In addition, the second echo command can be removed from the if structure, because of the exit statements all lines after fi are only executed if the condition is met.

In principle, it is also possible to create single-line if-constructions, for example so:

In the code above, notice the semicolon after echo that is now required. Especially Such constructions are of course not easy to read. Better for simple cases this construction is suitable, which is equivalent to the above if:

This is where the logical AND operator is used instead of if: First, with […] checked the condition. The command is only given when this is fulfilled executed after &&.


test condition in bash programming:

In bash it is not possible to specify conditions directly in the formif $ a> 1. On the one hand, bash is based on the fact that all actions have a uniform command concept on the other hand are special characters like> and <already reserved for the rerouting of inputs and outputs. For this reason you need to formulate conditions in loops and branches Use the bash command test.

test returns 0 (true) if the condition is fulfilled or 1 (false), if the condition is not met. To reduce the writing effort, a Short notation provided in square brackets. test is primarily used in three areas: to compare two numbers, to compare strings and to test whether a file exists and has certain properties (see Table 1).

Table 1: The most important expressions for formulating conditions

Test printout Importance
[ zk ] true if the string is not empty
[ -n zk ] as above
[ zk1 = zk2 ] true if the strings match
[ z1 -eq z2 ] true if the numbers are equal
[ z1 -ne z2 ] true if the numbers are not equal
[ z1 -gt z2 ] true if z1 is greater than z2
[ z1 -ge z2 ] true if z1 is greater than or equal to z2
[ z1 -lt z2 ] true if z1 is less than z2 (less than)
[ z1 -le z2 ] true if z1 is less than or equal to z2
[ -d dat ] true if dat is a directory (directory)
[ -f dat ] true if dat is a file (file)
[ -r dat ] true, if the file can be read (read)
[ -w dat ] true, if the file can be changed (write)
[ dat1 -nt dat2 ] true if file 1 is newer than file 2 (newer than)

The following examples show three use cases. A reference to all test As usual, there are possible uses for test.

  • test “$ x” checks whether x is occupied. The result is false if the string is Has 0 characters, otherwise it is true.
  • test $ x -gt 5 tests whether the variable x contains a numerical value greater than 5. If x does not contain a number, an error message appears. Instead of Comparison operators -eq, -ne, -lt, -le and -ge can be used.
  • test -f $ x tests whether a file with the name given by x exists.

Instead of test expression, the short form [expression] is usually used. But don’t forget between the square brackets and specify at least one space on both sides of the printout! Whether you are with test or […] work: Remember that bash syntax has a semicolon asks for the condition: if [$ a -gt 1] then … is syntactically incorrect, esmuss if [$ a -gt 1]; then … hot!


case in bash programming:

case constructions are introduced with the keyword case. This is followed by the Parameter you want to analyze. Usually given in a variable. After the keyword in there can be several possible pattern strings with which the parameter is compared. They are the same Wildcards as allowed for file names.

Each pattern ends with a round bracket. – *) recognizes i.e. strings, that start with two minus signs. Multiple patterns can be identified by | separated from each other. In this case, both patterns are tested. For example * .c | * .h) is used to recognize * .c and * .h files in the same branch. The commands following the bracket must be terminated by two semicolons will. If an else branch is required, the last pattern must be * specified – all strings correspond to this pattern. When processing of a case construction, only the first branch is considered, in which the Parameter corresponds to the specified pattern.

The following example shows the use of case to classify the transferred Parameters in filenames and options. The loop for variable i is for executed all parameters that you passed to the script. Within this

In the loop, every single parameter is analyzed with case. If the parameter starts with starts with a hyphen, the parameter is appended to the end of the variable opt, otherwise to the end of dat.

An example run of the script proves the effectiveness of this simple case distinction. The parameters that are passed randomly in their order are turned into Options and filenames:

You can use case branches for classification purposes using the same scheme from certain file IDs by entering * .abc in the search pattern.


for loop in bash programming:

Bash knows three commands for creating loops: for executes a loop for select all elements of a specified list. while loops until the specified condition is no longer met. until does the loop like this long until the condition is met for the first time. All three loops can be break to be left prematurely. continue skips the rest of the loop body and continues the loop with the next loop pass. The following Lines summarize the syntax of for:

for loops can also be formulated as a single line. Then the command must be terminated with a semicolon within the loop:

 

The first example assigns the character strings a, b and c to the variable i in sequence. The body of the loop between do and done outputs the content of the variable:

The equivalent multi-line formulation of the above command in a script File would look like this:

The list for for can also be used with wildcards for file names or with {..} constructions to create strings. The following example uses all * .jpg files copied into * .jpg.bak files:

You often need loops to work through a text file line by line. No problem: Just pass the result of cat file to the keyword in! The The following mini-program is created for all databases that are entered line by line in the dbs.txt file a compressed backup in the file dbname.sql.gz:

With for loops without in … the loop variables are all sequentially with Pass specified parameters to script call; so this corresponds in $ *. An example for such a loop, see the description of case.



while and until loop in bash programming:

The following lines summarize the syntax for while and until loops:

In the following example, the value 1 is assigned to the variable i. Then will the variable in the loop body is increased by 1 between do and done until the value 5 is exceeded. You formulate the loop condition as with ifmit test or With [ … ]. So the mini-program outputs the numbers 1, 2, 3, 4 and 5:

With the single-line while variant, you must not forget the semicolon before done!

The following loop processes all * .jpg files in the local directory. There becomes the result of ls with the pipe operator | passed to while:

You can also use while to process all lines of a text file. Use for this Use the <operator to redirect the contents of the text file to the while loop. In the loop reads read one line at a time – until it reaches the end of the text file becomes:

The only difference between until loops and while loops is that that the condition is formulated logically negated. The following command gives as the first while example selects the numbers 1 to 5:


break and continue condition in bash programming:

You can end all bash loop variants prematurely with break. continue skips all commands up to done, but then continues the loop. The following example shows an application of break and continue. In the for loop, the variable i should run through the values ​​from 1 to 10. rest contains the rest the integer division by 2. With [$ rest -eq 1] the script tests whether the remainder 1 is whether i is an odd number. In this case it will be skipped the following commands with continue. echo returns the content of I out. When i reaches the value 6, the loop is ended with break. So there is Program the numbers 2, 4 and 6.

functions in bash programming:

The keyword function defines a subfunction that is like a new command can be called. The function code must be in curly brackets be set. You can use local to define local variables within the function. Functions can be called recursively and they must precede their be declared first call! Parameters can be passed to functions. Unlike many programming languages the parameters are not put in brackets. Within the Function the parameters can be taken from the variables $ 1, $ 2. This means, a function processes parameters in the same way as a bash script. The following mini script gives HelloWorld, Raspberry Pi! out:

The function keyword is optional. If function is not used, then The function name is followed by two round brackets. Thus the following is Program equivalent to the previous example:


Dealing with errors in  bash programming:

In most programming languages, the following applies: As soon as an unhandled error occurs, the program is ended. Bash scripts are much more relaxed: That Errors happen when executing commands, is accepted as something everyday. Executing the script becomes easy with the next statement continued.

However, this does not apply to obvious syntax errors, e.g. for a for loop without done or for a character string that begins with “with the second” character but missing: In such cases, bash can no longer manage the program structure decrypt: it displays an error message and cancels the code execution. Instructions up to the first syntax error are also executed in this case. When after a command you want to determine if it executed correctly or not, evaluate the predefined variable $ *. It contains the error code of the last command. The value 0 means that everything is okay was (see Table 2).

Even if the high fault tolerance of bash is often convenient – sometimes you want, that a script terminates at the first error and not possibly more subsequent errors produced. You can do this by adding set -e to the code. From this Position errors lead to an immediate end. If this strict error checking for the entire script should apply, specify the option -e in the first line:

Set -e or the bash option -e only apply to linked commands for the overall result If in the following example cmd1 fails – even if it is because that the command does not even exist – cmd2 is then executed. Only if also this command leads to an error, the script is aborted.

exit command in bash programming:

exit ends the running script. The script gives the return value of the last executed commands. If you don’t want that, you can go to exit explicitly pass a value. The value 0 is used to ensure that the To signal the end of the program. All other numbers indicate an error (see table 2).

Table 2: Usual exit codes

exit code Importance
0 OK, no error
1 General error
2 Error in the parameters passed
3–255 other errors, meaning program-specific


Response to signals (trap)

The concept of process management under Unix / Linux provides that processes Signals can be sent (see table 3). Lists even more signals kill -l. For example, if you press (Ctrl) + (C) while running a bash script press, the SIGINT signal is sent and the script execution is aborted.

Table 3:The most important signals

Signal name code Importance
SIGHUP 1 Request to read the configuration again
SIGINT 2 Interrupted by (Ctrl) + (C)
SIGKILL 9 kill signal, cannot be intercepted.
SIGTERM 15 Request to exit the program

With trap you can react specifically to such signals. The syntax of trap is simple:

trap ‘commands’ signals

commands specifies one or more commands to be executed when one of the signals listed is received. The signals can optionally through by their names or by their codes. If you have complex code in To respond to a signal, define the code in a function and specify the function name in the trap command. trap is often used to protect against a program termination triggered by a signal triggered to perform cleanups. For example, you can use a Delete temporary file With the simple command trap ” 2 you achieve that Your script (Ctrl) + (C) just ignored it.

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: