linux shell循环:for、while、until用法详解

2019-09-23 08:51:54刘景俊

用文件名做为参数,统计所有参数文件的总行数

[root@centos6mini 3.19]# ./linshi /etc/passwd /etc/sysconfig/network-scripts/ifcfg-eth1 /etc/passwd
89
[root@centos6mini 3.19]# cat linshi 
#!/bin/bash
sumhang=0
while [ $# -gt 0 ];do
    hang=$( cat $1 | wc -l )
    let sumhang+=hang
    shift
done
echo $sumhang

4、用二个以上的数字为参数,显示其中的最大值和最小值

方法一:

#!/bin/bash
min=$1 #最小值等于第一个数值
max=$1 #最大数等于第一个数值

while [ $# -gt 0 ];do  #进行数值数量进行判断,做循环
    value=$1   #定义变量
    if [ $value -gt $max ];then  #当第二个数大于第一个数时
        max=$value #最大值等于后一个数值,对max从新赋与新的值
    elif [ $value -lt $min ];then  #当第二个数大于第一个数时
        min=$value  #最小值等于后一个数值 对min从新赋与新的值
    fi
    shift #不管前面判断是否成立,都进行数列左移,
done
echo "min $min"
echo "max $max"

方法二:

#!/bin/bash
if [ $# -lt 2 ];then #对输入数字数量进行检测
    echo "type more than two numbers"
    exit 1
fi

small=$(echo $* |xargs -n1 |sort -n |head -n 1)  #进行数值排序
big=$(echo $* |xargs -n1 |sort -n |tail -n 1)
echo "Maximum number is $big"
echo "Minimum number is $small"

[root@localhost ~]# echo 1 -3 -99 46 7 32 43 2133 312 |xargs -n1 #以一数列进行显示
1
-3
-99
46
7
32
43
2133
312

read 示例:

[root@centos6mini 3.19]# while read -p "type your name: " name ;do echo your is $n$name; done
type your name: zhangsan
your is zhangsan
type your name: lisi
your is lisi
type your name: wangwu
your is wangwu
type your name: ^C

[root@centos6mini 3.19]# read bing < test。txt
[root@centos6mini 3.19]# echo $bing  
hello

^C
[root@centos6mini 3.19]# while read name ; do echo $name ;done # 没有指定输入
123   #输入
123   #输出
qwe    #输入
qwe   #输出
asd   #输入
asd   #输出
zxc   #输入
zxc   #输出
^C^[[A^C
[root@centos6mini 3.19]# while read name ; do echo $name ;done <6  #name为变量,输入来自文件文件内容读取完了,循环停止
hello
qweqew
12341234
asdas
ads
sda
sad
asd
as
asd
as

read 示例:
显示UID小于1000的为sys user,大于等于1000的为comm user。

[root@centos6mini 3.19]# cat linshi    
#!/bin/bash
while read usline ;do #通过read ,定义变量值usline
    usuid=$( echo $usline |cut -d: -f3 ) ,#引用变量usline ,并定义变量usuid
    usname=$( echo $usline |cut -d: -f1 ) #引用变量usline ,并定义变量usname
    #if [ $usuid -lt 1000 ];then  #进行判断
    if (( $usuid < 1000 )) ;then  #进行判断(两种方式均可以)
        echo "$usname is a sys user"
    else 
        echo "$usname is a comm user"
    fi

done < /etc/passwd #每次循环引用文件内容一行,进行操作,引用完了,循环停止。
[root@centos6mini 3.19]# ./linshi  
root is a sys user
bin is a sys user
daemon is a sys user
adm is a sys user
lp is a sys user
sync is a sys user
shutdown is a sys user
halt is a sys user
mail is a sys user
uucp is a sys user
operator is a sys user
games is a sys user
gopher is a sys user
ftp is a sys user
nobody is a sys user
vcsa is a sys user
saslauth is a sys user