Bash C Style For Loop Example and Syntax

How do I use the bash C style for loop under UNIX or Linux operating systems?

The bash C-style for loop share a common heritage with the C programming language. It is characterized by a three-parameter loop control expression; consisting of an initializer (EXP1), a loop-test or condition (EXP2), and a counting expression (EXP3). The syntax is as follows:

for (( EXP1; EXP2; EXP3 ))

Bash C-Style Example

# Display message 5 times
for ((i = 0 ; i < 5 ; i++)); do
  echo "Welcome $i times."

Sample outputs:

Welcome 0 times.
Welcome 1 times.
Welcome 2 times.
Welcome 3 times.
Welcome 4 times.

Read An Array Using C Style For Loop

Bash provides one-dimensional array variables. An array is created automatically using the following compound assignments syntax:

array=( item1 item2 item3 ... itemN)

You can read an array using for loop as follows:

# define an array called fruits
fruits=("Apple" "Mango" "Pineapple" "Banana" "Orange" "Papaya" "Watermelon")
len=${#fruits[*]}         # get total elements in an array
# print it
for (( i=0; i<${len}; i++ ));
	echo "${fruits[$i]}"

Here is another practical example that generates lighttpd web server configuration file to log real IP address of the visitors:

_frontend_proxy_lan_ips=("" "" "" "" "")
at=${#_frontend_proxy_lan_ips[*]}         # get total elements in an array
echo '### Log real client ips on all backends ###' >"$t"
echo 'server.modules += ( "mod_extforward" )'   >>"$t"
echo 'extforward.headers = ("X-Forwarded-For")' >>"$t"
echo 'extforward.forwarder = (' >>"$t"
# For loop 
for (( i=0; i<${at}; i++ ));
	[ $i -lt $(( $at - 1 )) ] && s="," || s=""      # remove , for last item in an array
        echo "      "${_frontend_proxy_lan_ips[$i]}" => "trust"${s} " >>"$t"
echo ')' >>"$t"
# Copy it
cp -f "$t" /etc/lighttpd/
# remove temp file
[ -f "$t" ] && rm -f "$t"

Sample outputs (sample config file generated by above script):

### Log real client ips on all backends ###
server.modules += ( "mod_extforward" )
extforward.headers = ("X-Forwarded-For")
extforward.forwarder = (
      "" => "trust", 
      "" => "trust", 
      "" => "trust", 
      "" => "trust", 
      "" => "trust" 

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.