shell综合题

题目:

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

[root@localhost shell]# vim echo_color.sh 

#!/bin/bash

echo_color() {
    
    
if [ $# -eq 0 ];then
        echo -e "\e[31mFAILED\e[0m"
else
        echo -e "\e[32mOK\e[0m"
fi
}

echo_color $@

在这里插入图片描述

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

[root@localhost shell]# vim position.sh 

#!/bin/bash
err(){
    
    
if [ -z "$1" ];then
        echo "error"
        return 1
else
        return 0
fi
}
err $1
~                                                                                 
~    

在这里插入图片描述

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

[root@localhost shell]# vim max.sh 

#!/bin/bash
max(){
    
    
        if [ $1 -ge $2 ]
        then
                echo "最大值是$1"
        else
                echo "最大值是$2"
        fi
}
max $1 $2
~        

在这里插入图片描述

4、将密码文件的每一行作为元数赋值给数组

[root@localhost shell]# vim homework2_1.sh 

#!/bin/bash
array=(`cat /etc/shadow`)
echo ${array[*]}

5、使用关联数组统计密码文件中用户使用的不同类型shell的数量

[root@localhost shell]# vim homework2_2.sh 

#!/bin/bash
declare -A num 

for i in `cut -d : -f 7 /etc/passwd`
do
        let num[$i]+=1
done

for j in ${
    
    !num[@]}
do
        echo $j:${
    
    num[$j]}
done

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

[root@localhost shell]# vim homework2_3.sh 

#!/bin/bash
declare -A num 
for i in `ls /root/shell | cut -d . -f 2`
do
        let num[$i]+=1
done

for j in ${
    
    !num[@]}
do
        echo $j:${
    
    num[$j]}
done
~                                                               
~

请添加图片描述

7.你需要打印一个给定的数字的反序,如输入10572,输出27501,如果没有输入数据,应该抛出错误和使用脚本说明。

[root@localhost shell]# vim sequence.sh 

#!/bin/bash
read -p "请输入一串数字:" num
count=$num
tmp=0
result=0

if [ -z $num ]
then
        echo "没有输入数据,您应该在运行本脚本后根据提示信息输>入一串数字!"
        echo "本脚本需要实现,如输入10572,输出27501"
elif `echo $num | grep "[0-9]" &> /dev/null`
then
        while [ $num -gt 0 ]
        do
                tmp=`expr $num % 10`
                result=`expr $result \* 10 + $tmp`
                num=`expr $num / 10`
        done
        echo "$count的反序列是$result"                  
else
        echo "输入的不是数字!"
fi

在这里插入图片描述
脚本说明:
1.输入的数字为num
2.赋值 tmp=0, result=0 (反向和单个数字设置为0)
3.num % 10, 将得到最左边的数字
4.反向数字可以用这个方法生成result * 10 + tmp
5.对输入数字进行右位移操作(除以10)
6.如果num > 0, 进入第三步,否则进行第七步
7.输出result

8.写出SHELL函数RevertInput,函数必须获取三个参数,然后将三个参数倒序echo打印出来,函数必须检查参数个数的合法性,如果参数非法,打印”Illegal parameters”

对于下面的输入:
RevertInput “this is para1” para2 para3
应该输出:
para3
para2
this is para1
(注:需要注意第一个参数中的空格)

[root@localhost shell]# vim args.sh 

#!/bin/bash

RevertInput ()
{
    
    
        read -p "Please input three args:" num1 num2 num3

        if [ -z $num1 ] || [ -z $num2 ] || [ -z $num3 ]
        then
                echo "Illegal parameters"
        else
                echo "$num3"
                echo "$num2"
                echo "$num1"
        fi
}

RevertInput
~           

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_53715074/article/details/130018229
今日推荐