shell编程练习

1.编写函数,实现打印绿色OK和红色FAILED,判断是否有参数,存在为ok,不存在为Failed

#!/bin/bash
fun()
{
if [ $# -eq 0 ];then
        echo -e "${RED}FAILED ${NC}"
else
        echo -e "${GREEN}OK ${NC}"
fi
}
fun

2.编写函数,实现判断是否无位置参数,如无参数,提示错误

#!/bin/bash
fun(){
if [ $# -eq 0 ];then
        echo "error"
else
        echo "haveing"
fi
}
read -p "please input : " i
fun $i


3.编写函数实现两个数字作为参数,返回最大值

#!/bin/bash
fun(){
if [ $num1 -gt $num2 ];then
        echo "the num1 bigger"
elif [ $num1 -lt $num2 ];then
        echo "the num2 bigger"

else
        echo "equal"
fi
}
read -p "please input two nums:" num1 num2
fun $num1 $num2
~

4.编写函数,实现两个整数作为参数,计算加减乘除

#!/bin/bash
fun(){
echo a+b=$((a+b))
echo a-b=$((a-b))
echo a*b=$((a*b))
echo a/b=$((a/b))
}
read -p "please input int number:" a  b
fun $a $b

5.将/etc/shadow文件的每一行作为元数赋给数组

#!/bin/bash
num=`wc -l < /etc/shadow`
for i in `seq $num`
do
   arr[$i]=`head -$i /etc/shadow | tail -1`
done

for i in ${arr[*]}
do
  echo $i
done

6.使用关联数组统计文件/etc/passwd中用户使用的不同类型shell的数量

#!/bin/bash
declare -A shells
while read line
do
  type=`echo $line | cut -d : -f7`
  let shells[$type]++
done </etc/passwd
for i in ${!shells[@]}
do
        echo "$i : ${shells[$i]}"
done

7.使用关联数组按扩展名统计指定目录中文件的数量

read -p "请输入要查看的目录:" path
[ -z $path ]&& echo "输入错误:输入为空" && exit 1
cd $path
for i in `ls`
do
        if [ -d $i ]; then
          echo $i >>~/homework3/ceshi.txt
        fi
done
declare -A arroy
a=0
while read line
do
  let arroy[$a]++
done <~/homework/ceshi.txt
b=0
for b in ${!arroy[*]}
do
   echo "目录文件共有: ${arroy[$b]}"
done


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值