I have a sample server name listed in variable as below:
var="server-13"
I need to check if the 7th character on $var is number 1
whichenv=`echo "$var"| head -c 7 | tail -c 1`
if [[ $whichenv -eq "9" ]]; then
echo "9 found"
else
echo "9 Not Found"
fi
Output:
This works fine but fails only if the seventh character is a hyphen "-".
Can you please suggest how can I overcome this issue ?
[ "${var:7:1}" == 1 ]
must be enclosed in double quotes and compare strings.
Your code will work the same way.
-eq
does not exist in a double bracket expression, hence the syntax error. Either use (pattern matching)
if [[ $whichenv == 9 ]]
or (arithmetic comparison expression)
if (( whichenv == 9 ))
Note that whichenv does not contain the right value (this is not delivered by the head and tail utilities )
Try for example
whichenv=${var#*-}
To get the number behind the dash
--
Note: the OP was using a double bracket expression, where these quotes are not necessary..
With single brackets the correct expression is either (string comparison):
[ "$var" = 1 ]
or (numerical comparison)
[ "$var" -eq 1 ]
3 Likes