check if a string contains a text
Test in a script whether a string contains, starts with or matches something.
shelldevelopment
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.
ask for input in a script
Ask yes or no, read a password without showing it, or wait for an answer with a time limit.
check if a file or folder exists
Test in a script whether a path exists, is a file, a folder, empty or runnable.
find the script's own folder
Inside a script, find the folder the script is in, to reach files next to it.
get a file's name, folder and extension
Take a path apart in a script: the folder, the name, the name without its extension, the extension.