11 of shell programming: application practice of for loop statement

Keywords: Linux network

11, Application practice of for loop statement

(1) , for loop syntax

1) General grammar
 for variable name in variable value list
do
   Command...
done
 2) c-type for loop syntax
for(( exp1;exp2;exp3))
do
   Command...
done

(2) Example 1

Use for to print 1, 2, 3, 4 and 5 numbers vertically.

[root@centos6-kvm3 scripts]# cat 11-01.sh
#!/bin/bash
for n in {1..5}
do
 echo $n
done
[root@centos6-kvm3 scripts]# sh 11-01.sh
1
2
3
4
5
[root@centos6-kvm3 scripts]# 

(3) Example 2:

Only the sshd rsyslog crond network sysstat * * service can be set by developing script.

[root@centos6-kvm3 scripts]# cat 11-02.sh 
#!/bin/bash
for name in sshd rsyslog crond network sysstat
do
 chkconfig $name on
done
[root@centos6-kvm3 scripts]# chkconfig --list | grep 3:on
crond          	0:off	1:off	2:on	3:on	4:on	5:on	6:off
network        	0:off	1:off	2:on	3:on	4:on	5:on	6:off
rsyslog        	0:off	1:off	2:on	3:on	4:on	5:on	6:off
sshd           	0:off	1:off	2:on	3:on	4:on	5:on	6:off
sysstat        	0:off	1:on	2:on	3:on	4:on	5:on	6:off
//Extension:
[root@centos6-kvm3 scripts]# chkconfig --list | grep 3:on |awk '{print "chkconfig", $1, "off"}' | bash

(4) Example 3:

Calculate the sum from 1 to 100.

[root@centos6-kvm3 scripts]# cat 11-03.sh
#!/bin/bash
for n in {1..100}
do
  ((sum=sum+$n))
done
echo $sum
[root@centos6-kvm3 scripts]# sh 11-03.sh
5050
[root@centos6-kvm3 scripts]# 
//Method 2:
for ((i=1;i<=100;i++))
do
  ((sum=sum+$i))
done
echo $sum

(5) Case 4:

In Linux, modify the file name in batch, and remove "65104; finished" from the file name.

Prepare the test data as follows.

Method 1:
ls *.jpg | awk -F "_finished" '{print "mv",$0, $1$2}'|bash
//Method 2:
[root@centos6-kvm3 scripts]# cat 11-04.sh
#!/bin/bash
for file in `ls 11/*.jpg`
do
  mv $file `echo ${file/_finished/}`
done
[root@centos6-kvm3 scripts]# 
//Method 3:
rename "_finished" "" *.jpg

Posted by zorgon on Wed, 29 Apr 2020 07:05:43 -0700