redhat linux bash编程之交互编程

bash编程之交互编程

    read 
        -p "prompt"
        -t timeout

    例如:输入用户名,可返回其shell
        #!/bin/bash
        #
        read -p "Plz input a username: " userName

        if id $userName &> /dev/null; then
            echo "The shell of $userName is `grep "^$userName\>" /etc/passwd | cut -d: -f7`."
        else
            echo "No such user. stupid."
        fi

    例子:显示一个如下菜单给用户:
        cpu) show cpu infomation
        mem) show memory infomation
        *) quit

        1、如果用户选择了cpu,则显示/proc/cpuinfo文件的内容;
        2、如果用户选择了mem,则显示/proc/meminfo文件的内容;
        3、退出

            #!/bin/bash
            #
            echo "---------menu----------"
            echo "cpu) show cpu infomation"
            echo "mem) show memory infomation"
            echo "*) quit"
            echo "-------menu------------"

            read -p "Plz give your choice: " choice

            if [ "$choice" == 'cpu' ]; then
                cat /proc/cpuinfo
            elif [ "$choice" == 'mem' ]; then
                cat /proc/meminfo
            else
                echo "Quit"
                exit 3
            fi

            #!/bin/bash
            #
            cat << EOF
            -------menu------------
            cpu) show cpu infomation
            mem) show memory infomation
            *) quit
            -------menu------------
            EOF

            read -p "Plz give your choice: " choice

            if [ "$choice" == 'cpu' ]; then
                cat /proc/cpuinfo
            elif [ "$choice" == 'mem' ]; then
                cat /proc/meminfo
            else
                echo "Quit"
                exit 3
            fi


字串测试中的模式匹配
    [[ "$var" =~ PATTERN ]]

    例如:让用户给定一个用户名,判断其是否拥有可登录shell;
        /bin/sh, /bin/bash, /bin/zsh, /bin/tcsh, /sbin/nologin, /sbin/shutdown


        #!/bin/bash
        #
        read -p "Plz input a username: " userName
        userInfo=`grep "^$userName\>" /etc/passwd`

        if [[ "$userInfo" =~ /bin/.*sh$ ]]; then
            echo "can login"
        else
            echo "cannot login"
        fi

    练习:写一个脚本,完成如下功能
        使用格式:
            script.sh  /path/to/somefile

        1、可接受一个文件路径参数:
            如果此文件不存在,则创建之,则自动为其生成前n行类似如下:
                #!/bin/bash
                # description:
                # version:
                # date:
                # author: mageedu
                # license: GPL
            而后使用vim打开此文件,并让光标处在最后一行的行首
            如果文件存在、且是bash脚本,则使用vim打开之,光标自动处行最后一行的行首;
            否则,退出;

            如果正常编辑保存,
                判断,如果文件没有执行权限,则添加之;

                判断,其是否有语法错误,如果有,提示;
 

猜你喜欢

转载自blog.csdn.net/qq_40210617/article/details/86572195