Question
Using Bash, I have a string = "My string". How can I test if it contains another string? For example:
- if [ $string ?? 'foo' ]; then
- echo "It's there!"
- fi
How-To
You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:
- test.sh
- #!/bin/sh
- string="My long string"
- function contain()
- {
- echo -e "\t[Info] Check '$1' contains '$2'?"
- if [[ $1 == *"$2"* ]]; then
- echo "Hit!"
- else
- echo "Miss!"
- fi
- }
- contain "$string" "My long"
- contain "$string" "Missing string"
Note that spaces in the needle string need to be placed between double quotes, and the * wildcards should be outside the double quotes.
沒有留言:
張貼留言