Linux if and condition

Условные операторы if..else командной оболочки Bash

Bash if..else Statement

В этом руководстве мы познакомим вас с основами if оператора Bash и покажем, как его использовать в сценариях оболочки

Принятие решений — одна из самых фундаментальных концепций компьютерного программирования. Как и в любом другом языке программирования, if , if..else , if..elif..else и вложенные if в Bash могут быть использованы для выполнения кода на основе определенного состояния.

Условия Bash if могут иметь разные формы. Самое основное утверждение if принимает следующую форму:

Если TEST-COMMAND оценивается как True , STATEMENTS выполняется. Если TEST-COMMAND возвращается False , ничего не происходит, STATEMENTS игнорируется.

Как правило, рекомендуется всегда делать отступы для вашего кода и отделять блоки кода пустыми строками. Большинство людей предпочитают использовать отступы с 4 или 2 пробелами. Отступы и пустые строки делают ваш код более читабельным и упорядоченным.

Давайте посмотрим на следующий пример сценария, который проверяет, больше ли заданное число, чем 10:

Сохраните код в файле и запустите его из командной строки:

Скрипт предложит вам ввести номер. Например, если вы введете 15, test команда выполнит оценку, true потому что 15 больше 10, и echo команда внутри then условия будет выполнена.

if..else

Оператор Bash if..else принимает следующую форму:

Если TEST-COMMAND оценка до True , STATEMENTS1 будет выполнен. В противном случае, если TEST-COMMAND возвращается False , STATEMENTS2 будет выполнен. Вы можете иметь только одно else условие в объявлении.

Давайте добавим else условие в предыдущий пример сценария:

Если вы запустите код и введете число, сценарий напечатает другое сообщение в зависимости от того, больше это число или меньше / равно 10.

if..elif..else

Оператор Bash if..elif..else принимает следующую форму:

Вы можете иметь одно или несколько elif условий в объявлении. else Пункт не является обязательным.

Условия оцениваются последовательно. Как только условие возвращается, True остальные условия не выполняются, и управление программой переходит к концу if операторов.

Давайте добавим условие elif к предыдущему сценарию:

Вложенные if

Bash позволяет вам вкладывать if утверждения в if утверждения. Вы можете разместить несколько if операторов внутри другого if оператора.

Следующий скрипт предложит вам ввести три числа и напечатает наибольшее число среди трех чисел.

Вот как будет выглядеть вывод:

Как правило, более эффективно использовать case оператор вместо вложенных if операторов.

Несколько условий

Логические OR и AND операторы позволяют использовать несколько условий в if выражениях.

Вот еще одна версия скрипта для печати наибольшего числа среди трех чисел. В этой версии вместо вложенных if операторов мы используем оператор логического AND ( && ).

Тестовые операторы

В Bash команда test принимает одну из следующих синтаксических форм:

Чтобы сделать скрипт переносимым, предпочтите использовать старую [ команду test, которая доступна во всех оболочках POSIX. Новая обновленная версия test команды [[ (двойные скобки) поддерживается в большинстве современных систем, использующих Bash, Zsh и Ksh в качестве оболочки по умолчанию.

Читайте также:  Standard windows 10 icons

Чтобы отменить тестовое выражение, используйте логический оператор NOT ( ! ). При сравнении строк всегда используйте одинарные или двойные кавычки, чтобы избежать проблем с разбивкой слов.

Ниже приведены некоторые из наиболее часто используемых операторов:

  • -n VAR — Истина, если длина VAR больше нуля.
  • -z VAR — Правда, если VAR пусто.
  • STRING1 = STRING2 — Правда, если STRING1 и STRING2 равны.
  • STRING1 != STRING2 — Правда если STRING1 и STRING2 не равны.
  • INTEGER1 -eq INTEGER2 — Правда, если INTEGER1 и INTEGER2 равны.
  • INTEGER1 -gt INTEGER2 — Верно, если INTEGER1 больше чем INTEGER2 .
  • INTEGER1 -lt INTEGER2 — Правда, если INTEGER1 меньше, чем INTEGER2 .
  • INTEGER1 -ge INTEGER2 — Истинно, если INTEGER1 равно или больше, чем INTEGER2.
  • INTEGER1 -le INTEGER2 — Верно, если INTEGER1 равно или меньше чем INTEGER2 .
  • -h FILE — Истина, если FILE существует и является символической ссылкой.
  • -r FILE — Истинно, если FILE существует и доступно для чтения.
  • -w FILE — Истина, если FILE существует и доступна для записи.
  • -x FILE — True, если FILE существует и является исполняемым.
  • -d FILE — True, если FILE существует и является каталогом.
  • -e FILE — Истинно, если FILE существует и является файлом, независимо от типа (узел, каталог, сокет и т. Д.).
  • -f FILE — True, если FILE существует и является обычным файлом (не каталогом или устройством).

Вывод

Операторы if , if..else and if..elif..else позволяют контролировать поток выполнения скрипта Bash, оценивая заданные условия.

Источник

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”.

Читайте также:  Ksc 13 linux install

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

Читайте также:  Терминал linux основные команды

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”.

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 ‘94|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 ‘81’ 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|11|25|38|42|56’ 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.

Источник

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