Linux is case sensitive. Running "lsb_release -a" on my CentOS install results in "CentOS" - note that the trailing "S" is uppercase. Change your code to test for the properly capitalized string, and it should work.
if statement in bash not executing
-
23-06-2022 - |
Question
I am a beginner is bash and i really need some help here.The conditional part of the script is not executing for some reason. Here is my code
#!/bin/bash
#Checking Os
os=$(lsb_release -si)
echo $os
if [ $os == "CentOs" ]; then
echo 'success'
fi
Now part till echo $os works fine and out is
CentOs
but 'success' don't get output :(
Any idea why if part don't get executed.What is wrong with the syntax.I get no errors whatsoever
Solution
OTHER TIPS
Hope this helps:
#!/bin/bash
#Checking Os
os=$(lsb_release -si)
# !quote variables when passing them to commands like echo!
echo "$os"
# A space between ] and ; Quote "$os". Note: = instead of == is OK as well.
# Note that it's not CentOs, it's CentOS
if [ "$os" == "CentOS" ] ; then
echo 'success'
fi
The ultimate reference: Advanced Bash Scripting Guide
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow