I have a variable like below.
variable = This script is not found
if [[ "$variable" = ~ "not found" ]];
then
echo "Not Found"
else
echo "Its there"
if
while executing im getting below err,
line 4: syntax error in conditional expression
./test.sh: line 4: syntax error near `found"'
./test.sh: line 4: `if [[ "$variable" = ~ "not found" ]]; '
could anyone point me, What im missing here?
The easiest approach is to surround the substring with asterisk wildcard symbols (asterisk) * and compare it with the string. Wildcard is a symbol used to represent zero, one or more characters. If the test returns true , the substring is contained in the string.
To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.
Using the cut Command Specifying the character index isn't the only way to extract a substring. You can also use the -d and -f flags to extract a string by specifying characters to split on. The -d flag lets you specify the delimiter to split on while -f lets you choose which substring of the split to choose.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
Compare this with your version at the indicated points:
variable="This script is not found" # <--
if [[ "$variable" =~ "not found" ]] # <--
then
echo "Not Found"
else
echo "Its there"
fi # <--
You can't put spaces around = in an assignment, and you need to quote a string literal that has spaces. You don't need a trailing ; if you're going to put then on its own line. And an if-then ends with "fi" not "if".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With