Tutorial by Examples

if [[ $1 -eq 1 ]]; then echo "1 was passed in the first parameter" elif [[ $1 -gt 2 ]]; then echo "2 was not passed in the first parameter" else echo "The first parameter was not 1 and is not more than 2." fi The closing fi is necessary, but the eli...
#! /bin/bash i=0 while [ $i -lt 5 ] #While i is less than 5 do echo "i is currently $i" i=$[$i+1] #Not the lack of spaces around the brackets. This makes it a not a test expression done #ends the loop Watch that there are spaces around the brackets during the test (aft...
#! /bin/bash for i in 1 "test" 3; do #Each space separated statement is assigned to i echo $i done Other commands can generate statements to loop over. See "Using For Loop to Iterate Over Numbers" example. This outputs: 1 test 3
#! /bin/bash for i in {1..10}; do # {1..10} expands to "1 2 3 4 5 6 7 8 9 10" echo $i done This outputs the following: 1 2 3 4 5 6 7 8 8 10
The basic format of C-style for loop is: for (( variable assignment; condition; iteration process )) Notes: The assignment of the variable inside C-style for loop can contain spaces unlike the usual assignment Variables inside C-style for loop aren't preceded with $. Example: for (( i = ...
Until loop executes until condition is true i=5 until [[ i -eq 10 ]]; do #Checks if i=10 echo "i=$i" #Print the value of i i=$((i+1)) #Increment i by 1 done Output: i=5 i=6 i=7 i=8 i=9 When i reaches 10 the condition in until loop becomes true and the loop ends.
Example for continue for i in [series] do command 1 command 2 if (condition) # Condition to jump over command 3 continue # skip to the next value in "series" fi command 3 done Example for break for i in [series] do command 4 if (condi...
for loop: arr=(a b c d e f) for i in "${arr[@]}";do echo "$i" done Or for ((i=0;i<${#arr[@]};i++));do echo "${arr[$i]}" done while loop: i=0 while [ $i -lt ${#arr[@]} ];do echo "${arr[$i]}" i=$(expr $i + 1) done Or i=0...
Break multiple loop: arr=(a b c d e f) for i in "${arr[@]}";do echo "$i" for j in "${arr[@]}";do echo "$j" break 2 done done Output: a a Break single loop: arr=(a b c d e f) for i in "${arr[@]}";do e...
With the case statement you can match values against one variable. The argument passed to case is expanded and try to match against each patterns. If a match is found, the commands upto ;; are executed. case "$BASH_VERSION" in [34]*) echo {1..4} ;; *) seq -s" ...
for arg; do echo arg=$arg done A for loop without a list of words parameter will iterate over the positional parameters instead. In other words, the above example is equivalent to this code: for arg in "$@"; do echo arg=$arg done In other words, if you catch yourself wri...
How to use conditional execution of command lists Any builtin command, expression, or function, as well as any external command or script can be executed conditionally using the &&(and) and ||(or) operators. For example, this will only print the current directory if the cd command was succ...

Page 1 of 1