Bash C样式的循环示例和语法
时间:2020-01-09 10:42:04 来源:igfitidea点击:
在UNIX或者Linux操作系统下,如何使用bash C样式进行循环?
bash的C风格的for循环与C编程语言有着共同的传统。
它的特点是三参数循环控制表达式;由初始化程序(EXP1),循环测试或者条件(EXP2)和计数表达式(EXP3)组成。
语法如下:
for (( EXP1; EXP2; EXP3 )) do shell-command-1 shell-command-2 done
Bash C风格示例
#!/bin/bash # Display message 5 times for ((i = 0 ; i < 5 ; i++)); do echo "Welcome $i times." done
输出示例:
Welcome 0 times. Welcome 1 times. Welcome 2 times. Welcome 3 times. Welcome 4 times.
使用C样式进行循环读取数组
Bash提供一维数组变量。
使用以下复合赋值语法自动创建一个数组:
array=( item1 item2 item3 ... itemN)
您可以使用for循环读取数组,如下所示:
#!/bin/bash # 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++ )); do echo "${fruits[$i]}" done
这是另一个实际的示例,该示例生成lighttpd Web服务器配置文件以记录访问者的真实IP地址:
#!/bin/bash _frontend_proxy_lan_ips=("10.10.29.72" "10.10.29.71" "10.10.29.70" "10.10.29.69" "10.10.29.68") t="/tmp/lighttpd.backend.conf.$$" at=${#_frontend_proxy_lan_ips[*]} # get total elements in an array s="" 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++ )); do [ $i -lt $(( $at - 1 )) ] && s="," || s="" # remove , for last item in an array echo " \"${_frontend_proxy_lan_ips[$i]}\" - \"trust\"${s} " >>"$t" done echo ')' >>"$t" # Copy it cp -f "$t" /etc/lighttpd/ # remove temp file [ -f "$t" ] && rm -f "$t"
输出示例(上述脚本生成的示例配置文件):
### Log real client ips on all backends ### server.modules += ( "mod_extforward" ) extforward.headers = ("X-Forwarded-For") extforward.forwarder = ( "10.10.29.72" - "trust", "10.10.29.71" - "trust", "10.10.29.70" - "trust", "10.10.29.69" - "trust", "10.10.29.68" - "trust" )