Shellプログラミング、フロー制御、forループ1-21-9

6611 ワード

メモ


文法1
for   in  1  2  3...
	do
		 
	done
	
#!/bin/bash
# 
for time in morning afternoon evening 
	do 
		echo "This time is $time!"
	done
	
[root@localhost sh]# ./for.sh 
this time is moring!
this time is afternoon!
this time is evening!

#!/bin/bash
# 
cd /lamp 
ls *.tar.gz > ls.log 
for i in $(cat ls.log)
	do 
		tar -zxf $i &>/dev/null 
	done
rm -rf /lamp/ls.log


文法2
for ((  ; ;  ))
	do
		 
	done

#!/bin/bash
# 1 100
s=0
for (( i=1;i<=100;i=i+1 ))
	do
		s=$(( $s+$i ))
	done

echo "the sum of 1+2+...+100 is:$s"

[root@localhost ]# ./for2.sh
the sum of 1+2+...+100 is:5050

#!/bin/bash
# 

read -p "please input user name:" -t 30 name
read -p "please input number of users:" -t 30 num
read -p "please input the password of users:" -t 30 pass

if [ ! -z "$name" -a ! -z "$num" -a ! -z "$pass" ]
        then
                y=$(echo $num | sed 's/^[0-9]*$//g')
                if [ -z "$y"]
                        then
                        for (( i=1;i<=$num;i=i+1 ))
                                do
                                        /usr/sbin/useradd $name$i &>/dev/null
                                        echo $pass | /usr/bin/passwd --stdin "$name$i" &>/dev/null
                                done
                fi
fi