Bash script trouble with comparing strings - bash

I'm trying to compare strings. I get "command not found" error. How do I compare the strings?
Code:
#!/bin/bash
STR="Hello World"
if [$STR="Hello World"]; then
echo "passed test"
else
echo "didn't pass test"
fi
Output:
test.sh: line 4: [Hello: command not found
didn't pass test

You should add spaces. Treat [[ or [ as if it's another command like test and other builtins. And like other commands, it requires a space after its name. It's also recommended that you use [[ ]] over [ ] in Bash since [[ ]] doesn't split its variables with IFS and do pathname expansions. It also has more features over the other.
#!/bin/bash
STR="Hello World"
if [[ $STR = "Hello World" ]]; then
echo "passed test"
else
echo "didn't pass test"
fi

Related

How to check for space in a variable in bash?

I am taking baby steps at learning bash and I am developing a piece of code which takes an input and checks if it contains any spaces. The idea is that the variable should NOT contain any spaces and the code should consequently echo a suitable message.
Try this:
#!/bin/bash
if [[ $1 = *[[:space:]]* ]]
then
echo "space exist"
fi
You can use grep, like this:
echo " foo" | grep '\s' -c
# 1
echo "foo" | grep '\s' -c
# 0
Or you may use something like this:
s=' foo'
if [[ $s =~ " " ]]; then
echo 'contains space'
else
echo 'ok'
fi
You can test simple glob patterns in portable shell by using case, without needing any external programs or Bash extensions (that's a good thing, because then your scripts are useful to more people).
#!/bin/sh
case "$1" in
*' '*)
printf 'Invalid argument %s (contains space)\n' "$1" >&2
exit 1
;;
esac
You might want to include other whitespace characters in your check - in which case, use *[[:space:]]* as the pattern instead of *' '*.
You can use wc -w command to check if there are any words. If the result of this output is a number greater than 1, then it means that there are more than 1 words in the input. Here's an example:
#!/bin/bash
read var1
var2=`echo $var1 | wc -w`
if [ $var2 -gt 1 ]
then
echo "Spaces"
else
echo "No spaces"
fi
Note: there is a | (pipe symbol) which means that the result of echo $var1 will be given as input to wc -w via the pipe.
Here is the link where I tested the above code: https://ideone.com/aKJdyN
You could use parameter expansion to remove everything that isn't a space and see if what's left is the empty string or not:
var1='has space'
var2='nospace'
for var in "$var1" "$var2"; do
if [[ ${var//[^[:space:]]} ]]; then
echo "'$var' contains a space"
fi
done
The key is [[ ${var//[^[:space:]]} ]]:
With ${var//[^[:space:]]}, everything that isn't a space is removed from the expansion of $var.
[[ string ]] has a non-zero exit status if string is empty. It's a shorthand for the equivalent [[ -n string ]].
We could also quote the expansion of ${var//[^[:space:]]}, but [[ ... ]] takes care of the quoting for us.

conditional binary operator expected error when the file is empty in shell script

i have a file called MYNAME in path /root/user/
which has some value say SSS_14_10_1992
when the values exists in file the below code works fine
but when the file is empty , then the below mentioned error is thrown
i am reading this value from file and matching it wildcard and doing something , when the file has some value the below code works fine , when the file is empty then i am getting conditional error
Below is my code
var=$(cat /root/user/MYNAME)
echo $var
su - uname<<!
pwd
if [ -z "$var" ]; then
echo "NAME SHOULD BE PROVIDED IN MYNAME FILE"
else
if [[ $var == SSS_14_10* ]]
then
echo "value is matched"
else
echo "value has not matched"
fi
fi
!
when the file is empty
i am getting the below error:
: conditional binary operator expected
: syntax error near `SSS_14_10*'
: ` if [[ == SSS_14_10* ]]'
Try to compare "$var" (with quotes) instead of $var (without quotes). This way if the variable is empty you're just comparing "".
Don't generate code dynamically like this. Pass the value of $var as a parameter to the script run by su.
var=$(cat /root/user/MYNAME)
echo "$var"
su - uname<<'!' "$var"
pwd
if [ -z "$1" ]; then
echo "NAME SHOULD BE PROVIDED IN MYNAME FILE"
elif [[ $1 == SSS_14_10* ]]; then
echo "value is matched"
else
echo "value has not matched"
fi
!
Note the single quotes around the here-doc delimiter; this ensures the here document is seen as-is by su, so that nothing further needs escaping.

Shell If else with regex

I am using shell to simple String regex match. Here is my shell
#!/bin/sh
MSG="ANK"
PATTERN="([A-Z]{3,5}[-][0-9]{2,5})"
if [ "$MSG" =~ "$PATTERN" ]; then
echo "MATCHED";
else
echo "not";
fi
It is giving error
abc.sh: 6: [: ANK: unexpected operator
How should I fix this?
Making the changes proposed by several contributors in the comments yields:
#!/bin/bash
MSG="ANK"
PATTERN="([A-Z]{3,5}[-][0-9]{2,5})"
if [[ "$MSG" =~ $PATTERN ]]; then
echo "MATCHED";
else
echo "not";
fi
Note the change to bash, the change to [[ and removal of the quotation marks around $PATTERN.

Passing Argument in bash

I am having trouble to find the syntax error in the following script.
bash test.sh cat
#!/bin/bash
if [ $1 = "cat" ]; then
echo "valid"
else
echo "invalid"
fi
If you are not giving arguments, $1 will evaluate to a blank space and you are probably seeing line 2: [: =: unary operator expected. To fix, add quotes around $1:
#!/bin/bash
if [ "$1" = "cat" ]; then
echo "valid"
else
echo "invalid"
fi
This way, if you don't call with an argument it will still compare to an empty string.
In general, you should always put quotes around your variable expansions, otherwise you may see unexpected errors if the variable is empty (as you just saw) or if the variable has a space in it.
The arg $1 has no value. You could do something like this.
if [ -z $1 ]
then
echo "you forgot to give me an arg."
exit 1
fi
if [ $1 = "cat" ]; then
echo "valid"
else
echo "invalid"
fi
you can also do:
if [ $# -ne 1 ]; then
echo "Usage: ./script.sh <arg1>"
exit 1
fi

bash unexpected token then error

I have written a bash script and I am receiving an error when I am testing a condition whether a variable is empty or not.
Below is an example script:
I have not mentioned the commands that are executed to assign values to variables a and fne but
#! /bin/bash
for f in /path/*
do
a=`some command output`
fne=`this command operates on f`
if[ -z "$a" ]
then
echo "nothing found"
else
echo "$fne" "$a"
fi
done
error: syntax error near unexpected token, "then".
I tried another variation like this:
#! /bin/bash
for f in /path/*
do
a=`some command output`
fne=`this command operates on f`
if[ -z "$a" ]; then
echo "nothing found"
else
echo "$fne" "$a"
fi
done
again same error.
when I try comparing this way:
if[ "$a" == "" ]; then
again same error.
I am not sure what is the reason for the error. The value of variable a is like this:
Something with it (1) : [x, y]
it contains, spaces, brackets, comma, colon. I am enclosing the variable name in double quotes in comparison.
You are missing the space after the if:
#! /bin/bash
for f in /path/*
do
a=`some command output`
fne=`this command operates on f`
if [ -z "$a" ]; then
echo "nothing found"
else
echo "$fne" "$a"
fi
done
Side note: if you were using vi for editing, it would have syntax-colored your typo...

Resources