Problem:
while loop is a basic construct in many programming languages. Bash also allows us to use it to iterate over many things. Learn here how!
Solution:
The syntax of while loop is the following:
while test-commands; do consequent-commands; done
The loop is executed as long as test-commands has zero exit status. Return status of the loop is return status of the last command or zero if no command was executed.
Here’s an example:
#!/bin/bash echo "Number of params passed to the script: $#" function param_printer() { # $# is number of params passed to the function! while [ $# -gt 0 ]; do echo "Parameter inside a function: ${1}" # shift parameters by 1 effectively dropping the first one: shift done } # Pass all script parameters to the function: param_printer $@ # $# contains number of parameters while [ $# -gt 0 ]; do # print the first parameter echo "Parameter: ${1}" # shift parameters by 1 effectively dropping the first one: shift done
Note that function param_printer operates on a copy of parameters and shift doesn’t change the original script parameters!
Run the script and pass different number of arguments to how it works:
$> ./while-loop.sh Number of params passed to the script: 0 $> ./while-loop.sh a b c Number of params passed to the script: 3 Parameter inside a function: a Parameter inside a function: b Parameter inside a function: c Parameter: a Parameter: b Parameter: c
The while loop is very often used in Bash to process script parameters. We’ll cover that in a future post. Stay tuned! :-)