美文网首页
常用shell脚本

常用shell脚本

作者: 葫芦娃DayDream | 来源:发表于2020-03-17 11:32 被阅读0次
    shell脚本参数传递

    在shell脚本中$加一个数字,这个数字一定是参数的序号,不能随便编号。比如参数有五个,那这5个参数必须是$1 $2 $3 $4 $5。
    创建脚本文件 touch 01.sh
    打开脚本文件 vim 01.sh
    编写下面脚本代码:

    #!/bin/bash
    echo "参数 $1"
    echo "参数 $2"
    echo "参数长度 $#"
    

    echo是打印输出。
    退出脚本文件:回车换行 -> esc ->:wq!

    将脚本文件变成可执行文件 chmod u+x 01.sh
    下面我们执行脚本文件,传入参数
    ./01.sh 11 22 33

    执行的结果:
    参数 11
    参数 22
    参数长度 3

    遍历所有参数
    #!/bin/bash
    echo "参数 $1"
    echo "参数 $2"
    echo "参数 $3"
    echo "参数 $4"
    echo "参数长度 $#"
    for param in "$@"
            do
            echo "param:$param"
    done
    

    使用for循环来进行遍历,$@ 代表所有的参数的集合。
    打印结果:
    参数 11
    参数 22
    参数 33
    参数 44
    参数长度 5
    param:11
    param:22
    param:33
    param:44
    param:55

    if判断语句

    下面代码判断文件目录是否存在

    #!/bin/bash
    myDir=/usr/bin
    if [ -d $myDir ] && [ -d $HOME ]
    then
        echo "文件夹 存在"
        touch test.txt
    else
        echo "文件夹不存在"
    fi
    

    这里的-d 参数判断$myPath目录是否存在
    -d 检查是否存在,并且是一个目录
    -e 检查file是否存在
    -f 检查是否存在,并且是一个文件
    -r 检查是否存在 可读
    -w 检查文件是否可写
    多条件语句
    if后面一定加空格

    switch语句
    #!/bin/bash
    testUser=$1
    case $testUser in
    one)
            echo "tim";;
    two)
            echo "david";;
    *)
            echo "默认";;
    esac
    

    在shell脚本中switch语句没有switch这个关键字,默认的条件选项是*)。关键字esac表示结束。
    运行该脚本的语句(该脚本名称为03.sh):
    ./03.sh one
    运行结果:
    tim

    for循环
    #!/bin/bash
    for item in mother father brother
    do
            echo $item
    done
    
    list="mother father brother"
    for item in $list
    do
            echo $item
    done
    
    list="Mother,Father,Brother"
    IFS=$,
    for item in $list
    do
        echo $item
    done
    
    while循环
    #!/bin/bash
    a=10
    while [ $a -gt 0 ]
    do
        a=$[ $a - 1]
        echo "a:$a"
        if [ $a -eq 5 ]
        then
        echo "跳出循环"
        break
        fi
    done
    
    输出到文件
    #!/bin/bash
    file=test.txt
    
    echo "david">$file
    echo "tim">>$file
    

    > 输出重定向
    < 输入重定向
    '>!':如果存在则覆盖
    '>&':执行时屏幕上所产生的任何信息写入指定的文件中
    '>>':追加到文件中
    '>>&':屏幕上的信息追加到文件中

    相关文章

      网友评论

          本文标题:常用shell脚本

          本文链接:https://www.haomeiwen.com/subject/tbgzehtx.html