Linux bash script if and or

Bash Script | How to Use the Condition or with if Statement?

In Bash scripting for Linux, the “or” and “if” statements are used to control the flow of a script by allowing the user to specify conditions that must be met for certain commands to be executed. The “or” statement (||) allows the execution of a command if one of the multiple conditions is met, while the “if” statement allows the execution of a command if a single condition is met. In this article, we will discuss how to effectively use the “or” and “if” statements together in Bash scripting to create powerful and efficient scripts.

This guide will teach the audience about using the condition “or” with the “if” statement.

Using if Statement in Bash Script

We will first show you how to apply the if command to any bash script so you can understand it better. Afterward, we will show you how to incorporate it with the ‘or’ command in the next section.

A Bash script named “bashfile2.sh” is created. The code of it is shown in the snippet below:

#/bin/bash echo -n "Enter a number: " read No if [[ $No -gt 10 ]] then echo "Number is greater than 10. " else echo "The number is less than 10. " fi

Explanation of a Code:

We have started with a basic if command and are making a comparison here in which a user will provide any number as an input inside a ‘No’ variable. The “if” condition checks the entered number for being less or greater than 10.

If the condition is true, it will print ‘The number is greater than 10’; if not, ‘the number is less than 10’ using the echo command. Also, when you are using an if statement, you need to end its body by writing ‘fi’ otherwise, it will show you a syntax error.

To execute the above-created script, we used the following command:

After adequately understanding the syntax and usage of the if condition, let’s move to the ‘or’ condition combined with the ‘if’ statement in the next section.

Using “OR” With “if” in Bash

To use the ‘or’ condition in the bash program, you must write two straight vertical lines ( || ). It is used to compare at least two different conditions; if any of them are true, then their output will also be true.

Example 1: To Check If a Number is between 10 and 20

The basic example of the “or” and “if” combined is mentioned below:

#/bin/bash echo "Enter any number between 10 and 20" read No if [[ ( $No -lt 10 || $No -gt 20 ) ]] then echo "Number is not in range" else echo "You have entered $No" fi

Explanation of a Code:

In the code, the user will be asked to write a random number between 10 to 20. If a user writes any number that does not belong to this range, it will print ‘Number is not in range’; otherwise, it will display that number.

Читайте также:  Ftp сервер apache linux

Example 2: To Check If a Number is Even or Divisible by 5

In another example, we’d check whether the entered number is even or can be divided by five, and for that, we’ve created a bash file, as seen below.

#!/bin/bash echo -n "Enter a Number: " read num if [ $((num % 2)) == 0 ] || [ $((num % 5)) == 0 ]; then echo "You entered $num, which is either even or divisible by 5." else echo “You entered $num, which is not an even number or divisible by 5." fi

Explanation of the code:

Here we’ve asked the user to enter a number, and then the program will check if a number is even or divisible by 5 or not.

And now, we’ll execute the above-created script using this command.

We have executed the script two times where we first entered the number 3, and in this case, both conditions are false. In the section execution, we have entered 15 divisible by 5, so this condition is true.

By Logical OR (||), we mean that either one of the “if” statements are true, and the command(s) would be executed.

Conclusion

In Bash scripting for Linux, “or” and “if” statements are powerful tools that allow you to control the flow of a script by specifying conditions that must be met for certain commands to be executed. In this tutorial, we have demonstrated how to effectively use these statements together in Bash scripting, creating efficient and powerful scripts.

Источник

How to Use Logical OR & AND in Shell Script with Examples

Logical operators are used to combine multiple conditions in a script, allowing for more complex decision-making. The two most commonly used logical operators in shell scripting are Logical OR (||) and Logical AND (&&).

These operators are used in conditional statements like if, while, and until, as well as in command chaining. Command chaining is a technique where multiple commands are executed in a sequence, based on the success or failure of previous commands.

  • The Logical OR operator (||) is used to execute the command following it only if the previous command fails (returns a non-zero exit status).
  • The Logical AND operator (&&) is used to execute the command following it only if the previous command is successful (returns a zero exit status).

1. Using Logical OR (||) in Shell Scripts

Logical OR in bash script is used with operator -o. Write a small shell script that will show how to use logical OR ( || ) operator between two conditions.

This shell script prompts the user to input two numeric values. It then checks if either the first value is less than or equal to 10, or the second value is greater than 20. If at least one of these conditions is met, the script outputs “At least one condition is true.” Otherwise, it outputs “Both conditions are failed.”

Читайте также:  Linux halt vs shutdown

2. Using Logical AND (&&) in Shell Scripts

Logical AND in bash script is used with operator -a. Below shell script will show you to how to use logical AND ( && ) between two conditions.

This shell script prompts the user to input two numeric values. It then checks if the first value is less than or equal to 10 and the second value is greater than 20. If both conditions are met, the script outputs “Both conditions are true.” Otherwise, it outputs “At least one condition is false.”

3. Using Multiple Logical OR & AND

Now, use the multiple logical operators in a single statement. The below example will help you to understand how to use multiple logical operators in a single statement.

This shell script allows a user to input a number and then checks if the entered number lies within either the range of 10-20 or 100-200. The script then outputs a message to the user indicating whether the input number falls within one of these specified ranges or not.

4. A Practical Example

In this practical example, we’ll create a shell script that checks if a server is reachable and if a specific directory exists on the local machine. If both conditions are met, the script will create a backup of the directory and transfer it to the remote server using scp. If any of these conditions are not met, it will print an appropriate error message.

Create a file called backup_and_transfer.sh and add the following content:

This script demonstrates the use of Logical AND (&&) and Logical OR (||) operators to chain commands, create backup files, and transfer them to a remote server, while handling errors and providing useful feedback.

Conclusion

Mastering the Logical OR (||) and Logical AND (&&) operators in shell scripting enables you to create efficient and effective scripts for managing systems and automating tasks. By understanding their usage and combining them as needed, you can create complex decision trees and streamline your shell scripts. Remember to follow best practices, such as using parentheses to group conditions and leveraging short-circuit evaluation, to optimize your scripts and ensure they work as intended. With practice and a thorough understanding of these logical operators, you’ll be well on your way to becoming a shell scripting expert.

Источник

Bash OR Operator

Under Logical operators, Bash provides logical OR operator that performs boolean OR operation.

Bash boolean OR operator takes two operands and returns true if any of the operands is true, else it returns false.

OR logical operator combines two or more simple or compound conditions and forms a compound condition.

Syntax of OR Operator

Following is the syntax of OR logical operator in Bash scripting.

where operand_1 and operand_2 are logical expressions or boolean conditions that return either true or false. || is the operator used for AND boolean operation.

AND Truth Table

Following truth table gives information about the returned value by OR logical operator for different valid operand values.

Читайте также:  Linux how to forum
Operand_1 Operand_2 Operand_1 && Operand_2
true true true
true false true
false true true
false false false

Bash OR Operator in IF condition

In the following example, we shall use Bash OR logical operator, to form a compound boolean expression for Bash IF.

We shall check if the number is even or if it also divisible by 5.

Bash Script File

#!/bin/bash num=50 if [ $((num % 2)) == 0 ] || [ $((num % 5)) == 0 ]; then echo "$num is even or divisible by 5." fi
50 is even or divisible by 5.

Bash OR Operator in While Loop Expression

In this example, we shall use Bash OR boolean logical operator in while expression.

Bash Script File

#!/bin/bash a=1 b=1 a_max=7 b_max=5 # and opertor used to form a compund expression while [[ $a -lt $a_max+1 || $b -lt $b_max+1 ]]; do echo "$a" let a++ let b++ done

Conclusion

In this Bash Tutorial, we learned the syntax of Bash OR logical operator and how to use it in preparing compound expression for conditional statements or looping statements.

Источник

bash if with or and negation

print: WTF1 instead of nothing? It is especially perplexing that the second form works as expected and the first not.

3 Answers 3

tests whether the string in the middle is empty or not.

Since $wtf contains the string ‘false’ , the test returns true, or exit status 0 for success, because ‘false’ is not the same as the empty string » — and hence you get WTF1 as the response.

As pointed out by Gordon Davisson (and Dennis Williamson), it is a good idea to be careful with strings that you are testing. Indeed, I should have stated that I would always use [ -n «$wtf» ] or [ -z «$wtf» ] to test whether a variable is set, because that was necessary when I was learning shell, once upon a quarter century ago. I’ve had counter stories from Bash afficionados that you don’t have to worry about it in Bash — however, I think the code here provides a counter-example that in fact you do still have to worry about it.

  • Enclose tested variables in double quotes, or
  • (In Bash), use [[ $wtf ]] which does know how to handle the variable expansion.
  • Use the -n or -z tests to test for non-empty or empty values.

There can be exceptions to the rules — but you will not go far wrong following them.

wtf="1 -eq 0" [ $wtf ] && echo "WTF0" [[ $wtf ]] && echo "WTF1" wtf="false" [ $wtf ] && echo "WTF2" [[ $wtf ]] && echo "WTF3" wtf="" [ $wtf ] && echo "WTF4" [[ $wtf ]] && echo "WTF5" wtf="false" [ "$wtf" ] && echo "WTF6" [[ "$wtf" ]] && echo "WTF7" wtf="" [ "$wtf" ] && echo "WTF8" [[ "$wtf" ]] && echo "WTF9" 

with both bash and ksh (as found on MacOS X 10.6.4, when run with ‘bash testcode.sh’ or ‘ksh testcode.sh’). A real Bourne shell (if you can still find such a thing) would object to the double-bracket operations — it would not be able to find the command ‘ [[ ‘ on $PATH .

You can extend the testing to cover more cases ad nauseam.

Источник

Оцените статью
Adblock
detector