- Как сравнивать строки в Bash
- How to Compare Strings in Bash
- Это руководство описывает, как сравнивать строки в Bash.
- Операторы сравнения
- Проверьте, равны ли две строки
- Проверьте, содержит ли строка подстроку
- Проверьте, пуста ли строка
- Сравнение строк с помощью оператора Case
- Лексикографическое сравнение
- Вывод
- How to compare strings in Bash
- Example-1: String Comparison using “==” operators
- Example-2: String Comparison using “!=” operator
- Example-3: Partial String Comparison
- Example-4: Compare string with user input value
- About the author
- Fahmida Yesmin
- How to Compare Strings in Bash Shell Scripting
- Bash string comparison
- Check if two strings are equal
- Tip: Pay Attention on the spaces
- Check if strings are not equal in Bash
- Check if string is null or empty in Bash
- How to Compare Numbers and Strings in Linux Shell Script
- Compare Numbers in Linux Shell Script
- Compare Strings in Linux Shell Script
Как сравнивать строки в Bash
How to Compare Strings in Bash
Это руководство описывает, как сравнивать строки в Bash.
При написании сценариев Bash вам часто нужно сравнивать две строки, чтобы проверить, равны они или нет. Две строки равны, если они имеют одинаковую длину и содержат одинаковую последовательность символов.
Операторы сравнения
Операторы сравнения — это операторы, которые сравнивают значения и возвращают true или false. При сравнении строк в Bash вы можете использовать следующие операторы:
- string1 = string2 и string1 == string2 — Оператор равенства возвращает true, если операнды равны.
- Используйте = оператор с test [ командой.
- Используйте == оператор с [[ командой для сопоставления с образцом.
- string1 != string2 — Оператор неравенства возвращает true, если операнды не равны.
- string1 =
regex — Оператор регулярного выражения возвращает true, если левый операнд соответствует расширенному регулярному выражению справа.
- string1 > string2 — Оператор «больше чем» возвращает истину, если левый операнд больше правого, отсортированного по лексикографическому (алфавитному) порядку.
- string1 — Оператор less than возвращает true, если правый операнд больше правого, отсортированного по лексикографическому (алфавитному) порядку.
- -z string — Истина, если длина строки равна нулю.
- -n string — Истина, если длина строки не равна нулю.
Ниже следует отметить несколько моментов при сравнении строк:
- Пустое пространство должно быть использовано между бинарным оператором и операндами.
- Всегда используйте двойные кавычки вокруг имен переменных, чтобы избежать каких-либо проблем с разделением слов или смещениями
- Bash не разделяет переменные по «типу», переменные обрабатываются как целое число или строка в зависимости от контекста.
Проверьте, равны ли две строки
В большинстве случаев при сравнении строк вы хотите проверить, равны ли строки или нет.
Следующий скрипт использует оператор if и команду test, [ чтобы проверить, совпадают ли строки с = оператором:
Когда скрипт выполняется, он напечатает следующий вывод.
Вот еще один скрипт, который принимает входные данные от пользователя и сравнивает заданные строки. В этом примере мы будем использовать [[ команду и == оператор.
Запустите скрипт и введите строки при появлении запроса:
Вы также можете использовать логические и && и или || для сравнения строк:
Проверьте, содержит ли строка подстроку
Есть несколько способов проверить, содержит ли строка подстроку.
Один из подходов заключается в использовании подстроки с символами звездочки, * что означает совпадение всех символов.
Другой вариант — использовать оператор регулярного выражения, =
как показано ниже:
Точка, за которой следует звездочка, .* соответствует нулю или большему количеству вхождений любого символа, кроме символа новой строки.
Проверьте, пуста ли строка
Довольно часто вам также необходимо проверить, является ли переменная пустой строкой или нет. Вы можете сделать это, используя -n и -z оператор.
Сравнение строк с помощью оператора Case
Вместо использования тестовых операторов вы также можете использовать оператор case для сравнения строк:
Лексикографическое сравнение
Лексикографическое сравнение — это операция, в которой две строки сравниваются в алфавитном порядке путем сравнения символов в строке последовательно слева направо. Этот вид сравнения используется редко.
Следующие сценарии сравнивают две строки лексикографически:
Скрипт выведет следующее:
Вывод
Сравнение строк — одна из самых основных и часто используемых операций в сценариях Bash. Прочитав этот урок, вы должны хорошо понимать, как сравнивать строки в Bash. Вы также можете проверить наше руководство о конкатенации строк .
Источник
How to compare strings in Bash
For different programming purposes, we need to compare the value of two strings. Built-in functions are used in many programming language to test the equality of two strings. You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!=” is used to check inequality of the strings. You can partially compare the values of two strings also in bash. How you can compare the string values in bash is shown using various examples in this tutorial.
Example-1: String Comparison using “==” operators
There is no built-in comparison function to check equality of two string values in bash like other standard programming language. In the following script, two string variables, strval1 and strval2 are declared. The equity of these two string variables are tested using the first if statement of the script. The value of strval1 is compared with a string value to check the equality in the second if statement.
strval1 = «Ubuntu»
strval2 = «Windows»
#Check equality two string variables
if [ $strval1 == $strval2 ] ; then
echo «Strings are equal»
else
echo «Strings are not equal»
fi
#Check equality of a variable with a string value
if [ $strval1 == «Ubuntu» ] ; then
echo «Linux operating system»
else
echo «Windows operating system»
fi
Output:
First comparison is not equal and second comparison is equal.
Example-2: String Comparison using “!=” operator
The inequality of two string variables are checked in the following example. Here two values are not equal. So, if condition will be true and “Windows operating system” will print.
strval1 = «Ubuntu»
strval2 = «Windows»
#Check inequality of a variable with a string value
if [ $strval2 ! = «Ubuntu» ] ; then
echo «Windows operating system»
else
echo «Linux operating system»
fi
Output:
Example-3: Partial String Comparison
You can compare partial value by using wild card character in bash script. In the following script, “*” is used as wild card character for partial matching. The string variable, strval contains the word “Internet”. So, the first if of the script will return true and print “Partially Match”. Bash is case sensitive. For this, the second if of the script will return false for using “internet” as partial string which is not equal by letter wise comparison.
strval = «Microsoft Internet Explorer»
if [ [ $strval == * Internet * ] ] ;
then
echo «Partially Match»
else
echo «No Match»
fi
if [ [ $strval == * internet * ] ] ;
then
echo «Partially Match»
else
echo «No Match»
fi
Output:
Example-4: Compare string with user input value
Sometimes, we need to compare the string value taken by the user with specific string value for programming purpose. In the following example, a string data will be taken from user as input and compared the inequality of the data with a fixed value. If the condition is true then it will print “No Record Found”, otherwise it will print “Record Found”.
echo «Enter Your Name»
read input
if [ $input ! = «Fahmida» ] ;
then
echo «No Record Found»
else
echo «Record Found»
fi
Output:
Video of this lesson is here:
String comparison task in bash will be easier for you after completing the above examples with clear understanding.
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.
Источник
How to Compare Strings in Bash Shell Scripting
Dealing with strings is part of any programming language. Bash shell scripting is no different. Even the syntax is pretty much the same.
In this quick tutorial, I’ll show you how to compare strings in Bash shell scrips.
Bash string comparison
Here is how you compare strings in Bash.
You can also use a string directly instead of using a variable.
Let me show it to you with proper examples.
Check if two strings are equal
If you want to check if two strings are equal, here’s an example:
Tip: Pay Attention on the spaces
There must be a space between the [ and the variable name and the equality operator ==. If you miss any of the spaces here, you’ll see an error like ‘unary operator expected’ or missing `]’.
Check if strings are not equal in Bash
Instead of checking the quality, let’s do the opposite and check the inequality. Bash also provides the negation operator so that you can easily use “if not equal” condition in shell scripts.
The complete example looks like this:
Check if string is null or empty in Bash
Unlike some other languages like C++, in Bash you can check whether the string is null or empty with one single command:
The -z actually checks if length of the variable is zero or not. If the variable is not set or if it is empty (equal to “”), the length will be zero and hence the condition will return true.
A complete example can be seen here:
Note on the use of single bracket ‘[]’ and double bracket ‘[[]]’ in bash scripts
You can also use the if statement with double brackets like this:
The single bracket is the old Posix convention and it has some shortcomings. If you don’t use the double quotes around the variables and the variable is undefined, it will disappear from the code and this will result in syntax error.
If the variable $string1 is empty or not defined in the above code, that line will become equivalent to
Conclusion
I hope this quick little tutorial helped you in comparing strings in bash shell scripts. I recommend reading another quick tutorial on bash sleep command as well.
If you have questions or suggestions, feel free to leave a comment below.
Источник
How to Compare Numbers and Strings in Linux Shell Script
In this tutorial on Linux bash shell scripting, we are going to learn how to compare numbers, strings and files in shell script using if statement. Comparisons in a script are very useful & after comparison result, script will execute the commands and we must know how we can use them to our advantage.
Syntax of comparisons in shell script
This was just a simple example of numeric comparison & we can use more complex statement or conditions in our scripts. Now let’s learn numeric comparisons in bit more detail.
Compare Numbers in Linux Shell Script
This is one the most common evaluation method i.e. comparing two or more numbers. We will now create a script for doing numeric comparison, but before we do that we need to know the parameters that are used to compare numerical values . Below mentioned is the list of parameters used for numeric comparisons
- num1 -eq num2 check if 1st number is equal to 2nd number
- num1 -ge num2 checks if 1st number is greater than or equal to 2nd number
- num1 -gt num2 checks if 1st number is greater than 2nd number
- num1 -le num2 checks if 1st number is less than or equal to 2nd number
- num1 -lt num2 checks if 1st number is less than 2nd number
- num1 -ne num2 checks if 1st number is not equal to 2nd number
Now that we know all the parameters that are used for numeric comparisons, let’s use these in a script,
This is the process to do numeric comparison, now let’s move onto string comparisons.
Compare Strings in Linux Shell Script
When creating a bash script, we might also be required to compare two or more strings & comparing strings can be a little tricky. For doing strings comparisons, parameters used are
- var1 = var2 checks if var1 is the same as string var2
- var1 != var2 checks if var1 is not the same as var2
- var1 var2 checks if var1 is greater than var2
- -n var1 checks if var1 has a length greater than zero
- -z var1 checks if var1 has a length of zero
Note :- You might have noticed that greater than symbol (>) & less than symbol ( ” or “/ File comparison in Linux Shell Script
This might be the most important function of comparison & is probably the most used than any other comparison. The Parameters that are used for file comparison are
- -d file checks if the file exists and is it’s a directory
- -e file checks if the file exists on system
- -w file checks if the file exists on system and if it is writable
- -r file checks if the file exists on system and it is readable
- -s file checks if the file exists on system and it is not empty
- -f file checks if the file exists on system and it is a file
- -O file checks if the file exists on system and if it’s is owned by the current user
- -G file checks if the file exists and the default group is the same as the current user
- -x file checks if the file exists on system and is executable
- file A -nt file B checks if file A is newer than file B
- file A -ot file B checks if file A is older than file B
Here is a script using the file comparison
Similarly we can also use other parameters in our scripts to compare files. This completes our tutorial on how we can use numeric, string and file comparisons in bash scripts. Remember, best way to learn is to practice these yourself.
Источник