Linux if contain string

Bash Find Out IF a Variable Contains a Substring

Table of contents

Find out if bash variable contains a substring

Let us see various bash methods to check if a string contains a substring.

Using case syntax

You can use the portable BourneShell syntax as follows:

Here is a sample code:

Bash check if a string contains a substring

The [ and [[ evaluate conditional expression. This is a synonym for the test command/builtin. However, [[ is bash’s improvement to the [ command. Please note that the following is bash specific syntax and it will not work with BourneShell:

Here is a sample code:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Using bash regex syntax

Bash v3 and above also supports additional regular expressions. The syntax is as follows to see if bash variable contains a substring:

For example find out if a word ‘faq’ exists in $url:

Using AWK regex syntax

The syntax is pretty simple:

The grep command syntax

In this example I am going to use the grep to check if a string contains a substring in Bash script:

Let us try out the if command in our tiny shell script:

For example here is my LXD backup script that ignore containers from backup defined in the $ignore:

Conclusion

Checking if a variable contains a substring is useful in bash scripting. Of course, we can can use Perl, Python and more too. See your local bash man page for more information:
man bash
man grep
man awk

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Tutorial requirements
Requirements Linux/Unix with bash
Root privileges No
Difficulty Easy
Est. reading time 2m
Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

BASH Regular expression

‘.*cyberciti.biz.*’ ]] && echo Yes || echo No

BASH Regular expression

‘.*cyberciti.biz.*’ ]] && echo Yes || No

‘.*cyberciti.biz.*’ ]] && echo Yes || echo No

Wow plenty commenting on the bash regex. Well I just wanted to chime in there too. This is sufficient:

It should be noted that the pattern should NOT be quoted, else it is treated as a literal (yoander’s examples are, alas, incorrect)

I frequently do an arguments check at the start of my scripts to see if we should just print help and exit:

Edited by admin to correct syntax.

Of course, I forgot a ‘[‘ in my second example :-/

I had no idea about such a good bash syntax.

You need to pick a better font for displaying monospace text. The tildes (`

`) look way too similar to hyphens/dashes (`-`), I had to increase the font size and still I had difficulty verifying those were indeed tildes.

Источник

Как проверить, содержит ли строка подстроку в Bash

Одна из наиболее распространенных операций при работе со строками в Bash — определить, содержит ли строка другую строку.

В этой статье мы покажем вам несколько способов проверить, содержит ли строка подстроку.

Использование подстановочных знаков

Самый простой подход — окружить подстроку символами подстановки звездочки (звездочкой) * и сравнить ее со строкой. Подстановочный знак — это символ, используемый для обозначения нуля, одного или нескольких символов.

Если тест возвращает true , подстрока содержится в строке.

В приведенном ниже примере мы используем оператор if и оператор равенства ( == ), чтобы проверить, найдена ли подстрока SUB в строке STR :

При выполнении скрипт выведет:

Использование оператора case

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

Использование оператора Regex

Другой способ определить, встречается ли указанная подстрока в строке, — использовать оператор регулярного выражения =

. Когда используется этот оператор, правая строка рассматривается как регулярное выражение.

Точка, за которой следует звездочка .* Соответствует нулю или более вхождений любого символа, кроме символа новой строки.

Использование Grep

Команду grep также можно использовать для поиска строк в другой строке.

В следующем примере мы передаем строку $STR в качестве входных данных в grep и проверяем, найдена ли строка $SUB во входной строке. Команда вернет true или false в зависимости от ситуации.

Параметр -q указывает grep быть тихим и пропускать вывод.

Выводы

Проверка наличия в строке подстроки — одна из самых основных и часто используемых операций в сценариях Bash.

После прочтения этого руководства вы должны хорошо понимать, как проверить, включает ли строка другую строку. Вы также можете использовать другие команды, такие как awk или sed для тестирования.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

How to check if string contains numbers, letters, characters in bash

Table of Contents

bash check if string contains numbers. bash check string contains letters. bash check if string contains special characters. bash check if string starts with character. bash compare strings. shell script test variable is numeric. Check string only contains numbers. shell script to check whether a character is vowel or consonant. shell script to check if string contains vowels. bash check if string starts with character. bash check if string ends with character. shell script to check whether a character is alphabet digit or special character. bash check if string contains vowels. bash check if string starts with character. bash shell script to check if string contains numbers. shell script to check if string contains only numbers. shell script to check if string contains special characters.

Compare Strings in Bash

In my last article I shared some examples to get script execution time from within the script. I will continue with articles on shell scripts. In this article i will share examples to compare strings in bash and to check if string contains only numbers or alphabets and numbers etc in shell script in Linux. Now there can be various scenarios here, I will try to cover as many as possible.

1. Check if string contains numbers

Suppose you wish to compare strings and check if string contains numbers. Now this variable can also have characters, alphabets but most importantly we wish to check if string contains numbers. Use the below syntax in your script to compare strings and check if string contains numbers.

I will frame this in a script

Now let us execute our script, as you observe the script is able to differentiate between numerical and non numerical value

2. Check if string contains only numbers

Suppose you wish to compare strings and check if string contains only numbers. Now above we had a case where a string could contain both letter and alphabets. Try using the below syntax in your script to compare strings and check if string contains only numbers

I will frame this in a script to test multiple values

Now let us execute our script to compare strings, as you observe the script is able to differentiate between numerical and non numerical value so we are successfully able to check if string contains only numbers.

3. Check if string contains only alphabets and numbers

To compare strings and check if a string contains only alphabets and numbers you can use either of the below syntax.

Let me frame it in a script, i will demo only one of the syntax but both should work for you

Execute the script. As you see we are able to differentiate the strings with alphabets and numbers and without alphabets and numbers

4. Check if string starts with character

Here let me show you an example to compare strings to check if string starts with specific character or word. Now assuming I wish to make sure that a variable or string starts with character «A». Try the below syntax to check if string starts with character «A»

I will frame this in a script to test multiple values

Now let us execute our script, as you observe the script is able to check if string starts with character «A».

Similarly you can modify the logic to check for any other alphabet or character. For example to check for both small and capital alphabet use the below syntax

5. Check if string contains special characters

To compare strings and check if string contains special characters there are two methods. Either we match the pattern with all the available special characters or we do the opposite. We have a logic to check if a string contains only alphabets and numbers, we use that pattern and reverse it to get to know & check if string contains special characters.

Let us frame this pattern in a script

Now if we execute the script to check if string contains special characters, we observe that the script is able to tell us about the string with and without special characters.

6. Check if string contains vowels

Now to compare strings and check if string contains vowels we can use below pattern. Here we are defining all the vowels in the pattern to check if string contains vowels.

Let us put this in our script

Execute the script to verify the functionality and if our script is able to check if string contains vowels. As you observe now our script is able to identify and check if string contains vowels or it only contains consonant.

Lastly I hope the steps from the article to compare strings and check if string contains numbers, letters or special characters in shell script in Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

2 thoughts on “How to check if string contains numbers, letters, characters in bash”

what happens if I want to check if a string doesn’t contain it. Do you know the negative syntax of this comparison?

you can use NOT (!), for example [[ ! $VAR =

6 ]]; to check if VAR doesn’t contain any integers

Источник

Читайте также:  Свой словарь для mac os
Оцените статью