Difference between revisions of "Bash if elif else fi"

From thelinuxwiki
Jump to: navigation, search
Line 18: Line 18:
  
 
== example ==
 
== example ==
 +
<source lang="bash">
 
   if [ "$opt" = "some string" ]; then
 
   if [ "$opt" = "some string" ]; then
 
     some_command
 
     some_command
 
   fi
 
   fi
 
+
</source>
 
OR example
 
OR example
 
  <nowiki>
 
  <nowiki>
Line 31: Line 32:
  
 
if a variable contains a string...
 
if a variable contains a string...
 
+
<source lang="bash">
 
  string='foobar'
 
  string='foobar'
 
  if [[ $string == *"bar"* ]]; then
 
  if [[ $string == *"bar"* ]]; then
 
   echo "your bar is in my foo!"
 
   echo "your bar is in my foo!"
 
  fi
 
  fi
 +
</source>

Revision as of 13:16, 16 April 2021

Bash If..elif..else..fi

 if [ conditional expression1 ]
 then
   statement1
   statement2
   .
 elif [ conditional expression2 ]
 then
   statement3
   statement4
   .
   .
   .
 else
   statement5
 fi

example

  if [ "$opt" = "some string" ]; then
    some_command
  fi

OR example

 if [[ "$VARIABLE" == "something" || "$VARIABLE" == "else" ]]; then
   some_command
fi

conditional based on string compare

if a variable contains a string...

 string='foobar'
 if [[ $string == *"bar"* ]]; then
   echo "your bar is in my foo!"
 fi