Linux if statement with or

Bash conditional statement

Types of conditional statements

The following types of conditional statements can be used in bash.

  1. if statement
  2. if else statement
  3. if elif statement
  4. Nested if statement
  5. case statement

Each type of statements is explained in this tutorial with an example.

Conditional operators

Many conditional operators can be used in ‘if’ statement to do any conditional task. Some mostly used conditional operators are mentioned below.

Operator Description
-eq Returns true if two numbers are equivalent
-lt Returns true if a number is less than another number
-gt Returns true if a number is greater than another number
== Returns true if two strings are equivalent
!= Returns true if two strings are not equivalent
! Returns true if the expression is false
-d Check the existence of a directory
-e Check the existence of a file
-r Check the existence of a file and read permission
-w Check the existence of a file and write permission
-x Check the existence of a file and execute permission

Use of simple if statement

Syntax:

if [ condition ] ; then

Example-1: if statement with the single condition

This example shows the single conditional use of if statement. Create a file named ‘cond1.sh’ and add the following script. This script will take a numeric value as input and check the value is less than 100 or not by using if condition. If the condition is true then it will print a message in the terminal.

cond1.sh

Output:

Here, 87 is taken as input which is less than 100. So, the output is “87 is less than 100”. No output is printed for the input greater than 100.

Example-2: if statement with multiple conditions

How you can apply two conditions with logical AND in ‘if’ statement is shown in this example. Create a file named ‘cond2.sh’ and add the following script. Here, username and password will be taken from the user. Next, ‘if’ statement is used to check the username is ‘admin’ and the password is ‘superuser‘. If both values match then ‘if’ statement will return true and print the message “Login Successful”.

cond2.sh

Output:

The script will print no output for invalid input and print the success message for valid input.

Use of if-else statement

Syntax:

Example-3: if-else statement with multiple conditions

To execute one statement for true condition and another statement for the false condition, if-else statement is used in this example. Create a file named ‘cond3.sh’ and add the following script. Here, $name variable is used to take input from the user and the value of $name will be compared with two values, ‘Neha’ and ‘Nil’. If $name matches with any of these values then if condition will return true and the statement of ‘if’ part will be executed. If $name does not match with any of the values then if the condition will return false and the statement of ‘else’ part will be executed.

cond3.sh

Output:

The output is, “You have won the prize” for valid input and “Try for the next time” for the invalid input.

Use of if-elif-else statement

Syntax:

Example-4: if-elif-else statement to check different conditions

Multiple conditions with multiple if statements are declared in this example to print grade based on input mark. Create a file named ‘cond4.sh’ and add the following script. After taking the value of $mark, the first `if` statement will test the value is greater than or equal to 90. If it returns true then it will print “Grade – A+” otherwise it will go for the second condition. The second `if` will test the value is less than 90 and greater than or equal to 80. if it returns true then it will print “Grade – A” otherwise it will go for the third condition. If the third condition is true then it will print “Grade – B+” otherwise go for the fourth condition. If the fourth condition is true then it will print “Grade – C+” and if it returns false then the statement of else part will be executed that will print, “Grade – F”.

cond4.sh

Output:

The script is tested by three mark values. These are 95, 79 and 50. According to the conditions used in the script, the following output is printed.

Use of nested if

Syntax:

Example-5: Calculate bonus based on sales amount and duration

This example shows the use of nested if statement that will calculate bonus based on sales amount and time duration. Create a file named ‘cond5.sh’ and add the following code. The values of $amount and $duration are taken as input. Next, the first ‘if’ statement will check $amount is greater than or equal to 10000 or not. If it returns true then it will check the condition of nested ‘if’statement. the value of $duration is checked by the internal ‘if’ statement. If $duration is less than or equal to 7 then “You will get 20% bolus” message will be stored otherwise the message “You will get 15% bonus” will be stored in the $output variable. If the first ‘if’ condition returns false then the statements of else part will be executed. In the second nested ‘if’ condition, “You will get 10% bonus” message will print for returning a true value and “You will get 5% bonus” message will print for returning a false value.

cond5.sh

#!/bin/bash
echo «Enter the sales amount»
read amount
echo «Enter the time duration»
read duration

if ( ( $amount > = 10000 ) ) ; then
if ( ( $duration = 7 ) ) ; then
output = «You will get 20% bonus»
else
output = «You will get 15% bonus»
fi
else
if ( ( $duration = 10 ) ) ; then
output = «You will get 10% bonus»
else
output = «You will get 5% bonus»
fi
fi
echo » $output «

Output:

The script is tested by 12000 as amount and 5 as duration value first. According to the ‘if’ condition, the message, “You will get 20% bonus is printed. Next, the script is tested by 9000 as the amount and 12 as duration values and the message “You will get 5% bonus” is printed.

Use of case statement

Syntax:

Example-6: ‘case’ statement with a single value

‘case’ statement can be used as an alternative to ‘if’ statement. Create a file named ‘cond6.sh’ and add the following code to do some simple arithmetic operations. This script will read three values from the command line and store in the variables, $N1, $N2 and $op. Here, $N1 and $N2 are used to store two numeric values and $op is used to store any arithmetic operator or symbol. ‘case’ statement is used to check for four symbols to do any arithmetic operation. When $op is ‘+’ then it will add $N1 and $N2 and store the result in $Result. In the same way, ‘-‘ and ‘/’ symbols are used to do the subtraction and division operation. ‘x’ symbol is used here to do the multiplication operation. For any other value of $op, it will print a message, “Wrong number of arguments”.

Читайте также:  Загрузка linux помощью загрузчика windows

cond6.sh

Output:

Run the script with three command line arguments. The script is executed for four times by using four operators, ‘+’, ’-’, ‘x’ and ‘/’.

The following output will appear after running the script.

Example-7: ‘case’ statement with a range of values

‘case’ statement can’t define multiple conditions with the logical operator like ‘if’ statement. But using the pipe (‘|’), multiple conditions can be assigned in the ‘case’ statement. This example shows the grade value based on marks like Example-4 but using ‘case’ statement instead of ‘if’. $name and $mark values are given by command line arguments. The first condition is defined by ‘96|100’ for printing “Grade – A+”. This means if the $mark value is within 90-99 or 100 then the condition will be true. The second condition is ‘83’ for printing “Grade – A” and this will match $mark with any value from the range, 80-89. The third and fourth conditions work like the second condition. The fifth condition is ‘0|19|24|36|45|52’ for printing ‘Grade – F’ and it will match $mark with 0 or any number in the ranges 0-9, 10-19, 20-29, 30-39, 40-49 and 50-59.

cond7.sh

Output:

Run the script with two command line arguments. The script is run for four times with different argument values.

Conclusion:

Multiple uses of condition statements are tried to explain in this tutorial by using appropriate examples. Hope, the reader will be able to use conditional statements in bash script efficiently after practicing the above examples properly.

For more information watch the video!

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Conditions in bash scripting (if statements)

If you use bash for scripting you will undoubtedly have to use conditions a lot, for example for an if … then construct or a while loop. The syntax of these conditions can seem a bit daunting to learn and use. This tutorial aims to help the reader understanding conditions in bash, and provides a comprehensive list of the possibilities. A small amount of general shell knowledge is assumed. Difficulty: Basic – Medium

Let’s start your cloud journey

Looking to get certified or level up your cloud career? Learn in-demand cloud skills by doing with ACG.

Bash Programming Introduction

Bash features a lot of built-in checks and comparisons, coming in quite handy in many situations. You’ve probably seen if statements like the following before:

The condition in this example is essentially a command. It may sound strange, but surrounding a comparison with square brackets is the same as using the built-in test command, like this:

If $foo is Greater then or Equal to 3, the block after ‘then’ will be executed. If you always wondered why bash tends to use -ge or -eq instead of >= or ==, it’s because this condition type originates from a command, where -ge and -eq are options.And that’s what if does essentially, checking the exit status of a command. I’ll explain that in more detail further in the tutorial.There also are built-in checks that are more specific to shells. Whatabout this one?

The above condition is true if the file ‘regularfile’ exists andis a regular file. A regular file means that it’s not a block orcharacter device, or a directory. This way, you can make sure a usablefile exists before doing something with it. You can even check if afile is readable!

The above condition is true if the file ‘readablefile’ exists and is readable. Easy, isn’t it?

The syntax of an bash if statement

The basic syntax of an if … then statement is like this:

The condition is, depending on its type, surrounded by certainbrackets, eg. [ ]. You can read about the different types further onin the tutorial. You can add commands to be executed when the condition is false using the else keyword, and use the elif (elseif) keyword to execute commands on another condition if the primary condition is false. The else keyword always comes last. Example:

A short explanation of the example: first we check if the file somefile is readable (“if [ -r somefile ]”). If so, we read it into a variable. If not, we check if it actually exists (“elif [ -f somefile ]”). If that’s true, we report that it exists but isn’t readable (if it was, we would have read the content). If the file doesn’t exist, we report so, too. The condition at elif is only executed if the condition at if was false. The commands belonging to else are only executed if both conditions are false.

The basic rules of bash conditions

When you start writing and using your own conditions, there are some rules you should know to prevent getting errors that are hard to trace. Here follow three important ones:

    Always keep spaces between the brackets and the actual check/comparison. The following won’t work:

Bash will complain about a “missing `]’”.

  • Always terminate the line before putting a new keyword like “then”. The words if, then, else, elif and fi are shell keywords, meaning that they cannot share the same line. Put a “;” between the previous statement and the keyword or place the keyword on the start of a new line. Bash will throw errors like “syntax error near unexpected token `fi’” if you don’t.
  • It is a good habit to quote string variables if you use them in conditions, because otherwise they are likely to give trouble if they containspaces and/or newlines. By quoting I mean:

    There are a few cases in which you should notquote, but they are rare. You will see one of them further on in the tutorial.

    Also, there are two things that may be useful to know:

      You can invert a condition by putting an “!” in front of it. Example:

    Be sure to place the “!” inside the brackets!

    You can combine conditions by using certain operators. For the single-bracket syntax that we’ve been using so far, you can use “-a” for and and “-o” for or. Example:

    The above condition will return true if $foo contains an integer greater than or equal to 3 and Less Than 10. You can read more about these combining expressions at the respective condition syntaxes.

    Читайте также:  Не загружается windows после форматирования

    And, one more basic thing: don’t forget that conditions can also be used in other statements, like while and until. It is outside the scope of this tutorial to explain those, but you can read about them at the Bash Guide for Beginners.Anyway, I’ve only shown you conditions between single brackets so far. There are more syntaxes, however, as you will read in the next section.

    Different condition syntaxes

    Bash features different syntaxes for conditions. I will list the three of them:

    1. Single-bracket syntax

    This is the condition syntax you have already seen in the previous paragraphs; it’s the oldest supported syntax. It supports three types of conditions:

      File-based conditions

        Allows different kinds of checks on a file. Example:

      The above condition is true if the file ‘symboliclink’ exists and is a symbolic link. For more file-based conditions see the table below.

    String-based conditions

      Allows checks on a string and comparing of strings. Example one:

      The above condition is true if $emptystring is an empty string or an uninitialized variable. Example two:

      The above condition is true if $stringvar1 contains just the string “cheese”. For more string-based conditions see the table below.

    Arithmetic (number-based) conditions

      Allows comparing integer numbers. Example:

      The above condition returns true if $num is less than 1. For more arithmetic conditions see the table below.

      2. Double-bracket syntax

      You may have encountered conditions enclosed in double square brackets already, which look like this:

      The double-bracket syntax serves as an enhanced version of the single-bracket syntax; it mainly has the same features, but also some important differences with it. I will list them here:

        The first difference can be seen in the above example; when comparing strings, the double-bracket syntax features shell globbing. This means that an asterisk (“*”) will expand to literally anything, just as you probably know from normal command-line usage. Therefore, if $stringvar contains the phrase “string” anywhere, the condition will return true. Other forms of shell globbing are allowed, too. If you’d like to match both “String” and “string”, you could use the following syntax:

      Note that only general shell globbing is allowed. Bash-specific things like <1..4>or will not work. Also note that the globbing will not work if you quote the right string. In this case you should leave it unquoted.

      The second difference is that word splitting is prevented. Therefore, you could omit placing quotes around string variables and use a condition like the following without problems:

      Nevertheless, the quoting string variables remains a good habit, so I recommend just to keep doing it.

      The third difference consists of not expanding filenames. I will illustrate this difference using two examples, starting with the old single-bracket situation:

      The above condition will return true if there is one single file in the working directory that has a .sh extension. If there are none, it will return false. If there are several .sh files, bash will throw an error and stop executing the script. This is because *.sh is expanded to the files in the working directory. Using double brackets prevents this:

      The above condition will return true only if there is a file in the working directory called “*.sh”, no matter what other .sh files exist. The asterisk is taken literally, because the double-bracket syntax does not expand filenames.

      The fourth difference is the addition of more generally known combining expressions, or, more specific, the operators “&&” and “||”. Example:

      The above condition returns true if $num is equal to 3 and $stringvar is equal to “foo”. The -a and -o known from the single-bracket syntax is supported, too.Note that the and operator has precedence over the or operator, meaning that “&&” or “-a” will be evaluated before “||” or “-o”.

      The fifth difference is that the double-bracket syntax allows regex pattern matching using the “=

      ” operator. See the table for more information.

    3. Double-parenthesis syntax

    There also is another syntax for arithmetic (number-based) conditions, most likely adopted from the Korn shell:

    The above condition is true if $num is less than or equal to 5. This syntax may seem more familiar to programmers. It features all the ‘normal’ operators, like “==”, “ =”. It supports the “&&” and “||” combining expressions (but not the -a and -o ones!). It is equivalent to the built-in let command.

    Table of conditions

    The following table list the condition possibilities for both the single- and the double-bracket syntax. Save a single exception, the examples are given in single-bracket syntax, but are always compatible with double brackets.

    1. File-based conditions:

    Condition True if Example/explanation [ -a existingfile ] file ‘existingfile’ exists. if [ -a tmp.tmp ]; thenrm -f tmp.tmp # Make sure we’re not bothered by an old temporary filefi [ -b blockspecialfile ] file ‘blockspecialfile’ exists and is block special. Block special files are special kernel files found in /dev, mainly used for ATA devices like hard disks, cd-roms and floppy disks.if [ -b /dev/fd0 ]; thendd if=floppy.img of=/dev/fd0 # Write an image to a floppyfi [ -c characterspecialfile ] file ‘characterspecialfile’ exists and is character special. Character special files are special kernel files found in /dev, used for all kinds of purposes (audio hardware, tty’s, but also /dev/null).if [ -c /dev/dsp ]; thencat raw.wav > /dev/dsp # This actually works for certain raw wav filesfi [ -d directory ] file ‘directory’ exists and is a directory. In UNIX-style, directories are a special kind of file.if [ -d

    /.kde ]; thenecho “You seem to be a kde user.”fi [ -e existingfile ] file ‘existingfile’ exists. (same as -a, see that entry for an example) [ -f regularfile ] file ‘regularfile’ exists and is a regular file. A regular file is neither a block or character special file nor a directory.if [ -f

    /.bashrcfi [ -g sgidfile ] file ‘sgidfile’ exists and is set-group-ID. When the SGID-bit is set on a directory, all files created in that directory will inherit the group of the directory.if [ -g . ]; thenecho “Created files are inheriting the group ‘$(ls -ld . | awk ‘< print $4 >’)’ from the working directory.”fi [ -G fileownedbyeffectivegroup ] file ‘fileownedbyeffectivegroup’ exists and is owned by the effective group ID. The effective group id is the primary group id of the executing user.if [ ! -G file ]; then # An exclamation mark inverts the outcome of the condition following itchgrp $(id -g) file # Change the group if it’s not the effective onefi [ -h symboliclink ] file ‘symboliclink’ exists and is a symbolic link. if [ -h $pathtofile ]; thenpathtofile=$(readlink -e $pathtofile) # Make sure $pathtofile contains the actual file and not a symlink to itfi [ -k stickyfile ] file ‘stickyfile’ exists and has its sticky bit set. The sticky bit has got quite a history, but is now used to prevent world-writable directories from having their contents deletable by anyone.if [ ! -k /tmp ]; then # An exclamation mark inverts the outcome of the condition following itecho “Warning! Anyone can delete and/or rename your files in /tmp!”fi [ -L symboliclink ] file ‘symboliclink’ exists and is a symbolic link. (same as -h, see that entry for an example) [ -N modifiedsincelastread ] file ‘modifiedsincelastread’ exists and was modified after the last read. if [ -N /etc/crontab ]; thenkillall -HUP crond # SIGHUP makes crond reread all crontabsfi [ -O fileownedbyeffectiveuser ] file ‘fileownedbyeffectiveuser’ exists and is owned by the user executing the script. if [ -O file ]; thenchmod 600 file # Makes the file private, which is a bad idea if you don’t own itfi [ -p namedpipe ] file ‘namedpipe’ exists and is a named pipe. A named pipe is a file in /dev/fd/ that can be read just once. See my bash tutorial for a case in which it’s used.if [ -p $file ]; thencp $file tmp.tmp # Make sure we’ll be able to readfile=”tmp.tmp” # the file as many times as we likefi [ -r readablefile ] file ‘readablefile’ exists and is readable to the script. if [-r file ]; thencontent=$(cat file) # Set $content to the content of the filefi [ -s nonemptyfile ] file ‘nonemptyfile’ exists and has a size of more than 0 bytes. if [ -s logfile ]; thengzip logfile # Backup the old logfiletouch logfile # before creating a fresh one.fi [ -S socket ] file ‘socket’ exists and is a socket. A socket file is used for inter-process communication, and features an interface similar to a network connection.if [ -S /var/lib/mysql/mysql.sock ]; thenmysql –socket=/var/lib/mysql/mysql.sock # See this MySQL tipfi [ -t openterminal ] file descriptor ‘openterminal’ exists and refers to an open terminal. Virtually everything is done using files on Linux/UNIX, and the terminal is no exception.if [ -t /dev/pts/3 ]; thenecho -e “nHello there. Message from terminal $(tty) to you.” > /dev/pts/3 # Anyone using that terminal will actually see this message!fi [ -u suidfile ] file ‘suidfile’ exists and is set-user-ID. Setting the suid-bit on a file causes execution of that file to be done with the credentials of the owner of the file, not of the executing user.if [ -u executable ]; thenecho “Running program executable as user $(ls -l executable | awk ‘< print $3 >’).”fi [ -w writeablefile ] file ‘writeablefile’ exists and is writeable to the script. if [ -w /dev/hda ]; thengrub-install /dev/hdafi [ -x executablefile ] file ‘executablefile’ exists and is executable for the script. Note that the execute permission on a directory means that it’s searchable (you can see which files it contains).if [ -x /root ]; thenecho “You can view the contents of the /root directory.”fi [ newerfile -nt olderfile ] file ‘newerfile’ was changed more recently than ‘olderfile’, or if ‘newerfile’ exists and ‘olderfile’ doesn’t. if [ story.txt1 -nt story.txt ]; thenecho “story.txt1 is newer than story.txt; I suggest continuing with the former.”fi [ olderfile -ot newerfile ] file ‘olderfile’ was changed longer ago than ‘newerfile’, or if ‘newerfile’ exists and ‘olderfile’ doesn’t. if [ /mnt/remote/remotefile -ot localfile ]; thencp -f localfile /mnt/remote/remotefile # Make sure the remote location has the newest version of the file, toofi [ same -ef file ] file ‘same’ and file ‘file’ refer to the same device/inode number. if [ /dev/cdrom -ef /dev/dvd ]; thenecho “Your primary cd drive appears to read dvd’s, too.”fi

    2. String-based conditions:

    Condition True if Example/explanation [ STRING1 == STRING2 ] STRING1 is equal to STRING2. if [ “$1” == “moo” ]; thenecho $cow # Ever tried executing ‘apt-get moo’?fiNote: you can also use a single “=” instead of a double one. [ STRING1 != STRING2 ] STRING1 is not equal to STRING2. if [ “$userinput” != “$password” ]; thenecho “Access denied! Wrong password!”exit 1 # Stops script execution right herefi [ STRING1 > STRING2 ] STRING1 sorts after STRING2 in the current locale (lexographically). The backslash before the angle bracket is there because the bracket needs to be escaped to be interpreted correctly. As an example we have a basic bubble sort:(Don’t feel ashamed if you don’t understand this, it is a more complex example)array=( linux tutorial blog )swaps=1while (( swaps > 0 )); doswaps=0for (( i=0; i “$” ]; then # Here is the sorting conditiontempstring=$array[$i]=$array[$(( i + 1 ))]=$tempstring(( swaps=swaps + 1 ))fidonedoneecho $ # Returns “blog linux tutorial” [ STRING1

    With the double-parenthesis syntax, you can use the following conditions:

    5. Double-parenthesis syntax conditions:

    Condition True if Example/explanation (( NUM1 == NUM2 )) NUM1 is equal to NUM2. These conditions only accept integer numbers. Strings will be converted to integer numbers, if possible. Some random examples:if (( $? == 0 )); then # $? returns the exit status of the previous commandecho “Previous command ran succesfully.”fiif (( $(ps -p $pid -o ni=) != $(nice) )); thenecho “Process $pid is running with a non-default nice value”fiif (( $num NUM2 )) NUM1 is greater than NUM2. (( NUM1 >= NUM2 )) NUM1 is greater than or equal to NUM2. (( NUM1

    After this dry information load, here’s a bit of explanation for those who want to know more…

    Diving a little deeper

    I said I’d tell more about the fact that if essentially checks the exit status of commands. And so I will. The basic rule of bash when it comes to conditions is 0 equals true, >0 equals false.That’s pretty much the opposite of many programming languages where 0 equals false and 1 (or more) equals true. The reason behind this is that shells like bash deal with programs a lot. By UNIX convention, programs use an exit status for indicating whether execution went alright or an error occured. As a succesful execution doesn’t require any explanation, it needs only one exit status. If there was a problem, however, it is useful to know what went wrong. Therefore, 0 is used for a succesful execution, and 1-255 to indicate what kind of error occured. The meaning of the numbers 1-255 differs depending on the program returning them.Anyway, if executes the block after then when the command returns 0. Yes, conditions are commands. The phrase [ $foo -ge 3 ] returns an exit status, and the other two syntaxes as well! Therefore, there’s a neat trick you can use to quickly test a condition:

    In this example, “echo true” is only executed if “[ $foo -ge 3 ]” returns 0 (true). Why is that, you might ask. It’s because bash only evaluates a condition when needed. When using the and combining expression, both conditions need to be true to make the combining expression return true. If the first condition returns false, it doesn’t matter what the second one returns; the result will be false. Therefore, bash doesn’t evaluate the second condition, and that’s the reason why “echo true” is not executed in the example. This is the same for the or operator (“||”), where the second condition is not evaluated if the first one is true.Well, so much for the diving. If you want to know even more, I’d like to point you to the Advanced Bash-Scripting Guide and maybe the Bash Reference Manual, or even this System Administrator’s Guide to Bash Scripting.

    Conclusion

    In this tutorial, you’ve been able to make a start at understanding the many possibilities of conditions in bash scripting. You’ve been able to read about the basic rules of writing and using conditions, about the three syntaxes and their properties, and maybe you took the opportunity to dive a little deeper. I hope you enjoyed the reading as much as I enjoyed the writing. You can always return here to look up conditions in the table (bookmark that link to see the table directly), or to refresh your knowledge. If you have any suggestions, additions or other feedback, feel free to comment. Thanks for reading and happy scripting!

    Источник

    Читайте также:  C windows memory dmp можно ли удалить
  • Оцените статью