check if a string contains a text
Test in a script whether a string contains, starts with or matches something.
Steps
-
[[ $text == *"needle"* ]] && echo foundcontains needle
-
[[ $text == prefix* ]] && echo yesstarts with prefix
-
[[ $text =~ ^[0-9]+$ ]] && echo 'a number'matches a regular expression
-
grep -q 'needle' <<< "$text" && echo foundwith grep, also in sh
-
[[ -z $text ]] && echo emptyis empty
Notes
- [[ ]] is bash and zsh; in plain sh use case or grep.
Commands used
grep
Each has a page in lore: lore grep opens it.
Related recipes
- ask for input in a scriptAsk yes or no, read a password without showing it, or wait for an answer with a time limit.
- check if a file or folder existsTest in a script whether a path exists, is a file, a folder, empty or runnable.
- find the script's own folderInside a script, find the folder the script is in, to reach files next to it.
- get a file's name, folder and extensionTake a path apart in a script: the folder, the name, the name without its extension, the extension.