I'm having an issue with an if statement in a Bash script. Here's the code:
if [[ "$AppleID" -ne "" ]]; then
echo "<result>${AppleID}</result>"
else
echo "No user logged in."
fi
Assuming $AppleID is a string with a value of "test#email.com", the error message is as follows:
[[: test#email.com: syntax error: invalid arithmetic operator (error token is "#email.com")
I've tried using sed to escape the characters, like this:
if [[ `echo $(printf '%q' $AppleID) | sed -e 's/[\/&]/\\&/g'` -ne "" ]]; then
But I get the same error. How do I escape the # symbol?
-ne is for comparing integers. You want !=, or better yet, just use -n (which tests if its argument is a non-empty string):
if [[ -n "$AppleID" ]]; then
echo "<result>${AppleID}</result>"
else
echo "No user logged in."
fi
Related
I want to ensure that the given arguments are flags, by which I mean -x where x is some character or sequence of.
I have tried to do this with the following:
if [[ "$(echo '$1' | sed 's/[^-]//g')" -ne "-" ]];
then
echo "$usage"
exit
fi
Where my reasoning is that if - is not present when other characters are stripped it's not a flag.
This doesn't work though, and is obviously flimsy, but I don't know how to do this correctly.
# valid
script.sh -asdf
# invalid
script.sh sdf
You can do it this way to make sure $1 is starting with -:
if [[ "${1?}" != -* ]]; then
echo "$usage"
exit 1
fi
${1?} will fail the script if $1 is not available.
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.
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.
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.
I made a script to check tnsping but the if statement does not working properly. The following is the script:
ping=$(tnsping oracle1 |grep OK| awk -F" " '{print $1 }')
if [ -n $ping ]
then
echo "OK"
else
echo "NOT OK"
fi
If a execute change oracle for a non-existing oracle server I also receive "OK".
-n = The length of STRING is greater than zero
Wrap double quotes around $ping:
if [ -n "$ping" ]
then
echo "OK"
else
echo "NOT OK"
fi
Or it will undergo word splitting and globbing and resolve in the following arguments for [: '-n' and ']' when $ping is empty. which is the same as:
if [ '-n' '-n' ']'
See man test:
-n STRING
the length of STRING is nonzero
STRING
equivalent to -n STRING
-z STRING
the length of STRING is zero
And FYI you can omit the call to grep and use awk directly. And since the default Field Separator (-F) is space that can be omitted as well:
ping=$(tnsping oracle1 | awk '/OK/{print $1 }')
Neither the $ping variable nor awk are necessary, since grep can return an exit code to if:
if tnsping oracle1 | grep --quiet OK
then
echo "OK"
else
echo "NOT OK"
fi