- Условные операторы if..else командной оболочки Bash
- Bash if..else Statement
- В этом руководстве мы познакомим вас с основами if оператора Bash и покажем, как его использовать в сценариях оболочки
- if..else
- if..elif..else
- Вложенные if
- Несколько условий
- Тестовые операторы
- Вывод
- Conditions in bash scripting (if statements)
- Let’s start your cloud journey
- Bash Programming Introduction
- The syntax of an bash if statement
- The basic rules of bash conditions
- Different condition syntaxes
- 1. Single-bracket syntax
- 2. Double-bracket syntax
- 3. Double-parenthesis syntax
- Table of conditions
- 1. File-based conditions:
- 2. String-based conditions:
- 5. Double-parenthesis syntax conditions:
- Diving a little deeper
- Conclusion
Условные операторы 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 в качестве оболочки по умолчанию.
Чтобы отменить тестовое выражение, используйте логический оператор 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, оценивая заданные условия.
Источник
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 `]’”.
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.
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
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:
/.kde ]; thenecho “You seem to be a kde user.”fi
/.bashrcfi
2. String-based conditions:
With the double-parenthesis syntax, you can use the following conditions:
5. Double-parenthesis syntax conditions:
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!
Источник