Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to Find a substring in a bash shell script variable

Tags:

bash

shell

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?

like image 458
Boby Avatar asked Feb 27 '13 17:02

Boby


People also ask

How do you check if a variable contains a substring in bash?

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.

How do you find if a string contains a substring in shell script?

To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.

How do I select a substring in bash?

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.

What is $_ in bash?

$_ (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.


1 Answers

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".

like image 68
William Avatar answered Oct 13 '22 21:10

William