Saturday, January 22, 2022

bash tutorial part 2 - conditions

 okay, so conditions can be two : if/else/fi and case/esac.

firstly - if :

everytime we'll use if condition we'll need to use also fi. and mostly also else. why fi? every condition need to be ended. maybe most programming languages doesnt require closing it via fi or any other keyword (mostly its just either closing bracket or removing indentation) bash doesnt have it, so we need to end it. also compared parameters need to be closed in brackets. basically simplest if condition is:

if (compare); then

    (do something)

fi

 

 okay. and now more about brackets. this what we did wont really work with variables but with command outputs. so here a list which says what brackets and how much you should use:

[] - maths and comparing files

[[]] - advanced version of []

() - comparing results of executed commands in subshell 

(()) - comparing variables

if we'd use other action for something what should be done if condition isnt met we can also add else  like here:

if [compare];then

    (do something)

else

    (do something)

fi

 

now time for case. here also we need to end with esac (reversed case). all arguments are always written similar to a normal list of numbers, letters or words ended with ) . also actions need to end with double semicolon. basically it looks like this :

case (list of arguments) in

    x) (do everything here);;

    y) (do everything here);;

    z) (do everything here);;

    *) (else...);;

esac

 

small notes - you can nest if and case conditions inside other if or case conditions. just remember about indentation =]


you are gonna make conditions, yes? for if i think it'd be good to also say about maths in bash, i think it looks same or similar to other languages. so here we go:

for maths and text arguments:

= is same

!= is other than

for only maths:

< is smaller

> is bigger

>= is bigger or same

<= is smaller or same


also, creating arrays (lists):

its similar to creating variable, just that we put all arguments into brackets. if argument is longer than one word - we can put it in quotes, commas arent used. like:

array=(a b c ". . .")


and last thingy. script which after this and previous post you'll surely understand:

#!/usr/bin/env bash

x=a
y=(c d)
if (($x = b));then
        echo '1 you messed up'
else
        case $y in
                c) echo 'Hello World !!!';;
                *) echo '2 you messed up';;
        esac
fi



No comments:

Post a Comment