07. Shell脚本变量和参数

  • 变量

    变量基础

    1. shell的变量定义同标识符的定义规则
    2. shell中,取变量的值,需要用到$符,$变量名
    3. 变量的定义 变量名=变量值,注意,等号两边不可以有空格
    #! /bin/bash
    # print some infomation
    
    date1=`date +%H:%M:%S`
    echo "Begin at $date1"
    echo "Wait 2s !"
    sleep 2
    date2=`date +%H:%M:%S`
    echo "End at $date2"
    
    image.png

    数学运算

    1. 数学运算,需要使用[]将其包括
    2. 取数学运算的值,需使用字符$
    #! /bin/bash
    # Get the sum of numbers
    
    num1=1
    num2=2
    sum=$[$num1+$num2]
    echo "The result of sum : $num1+$num2=$sum"
    
    image.png

    用户交互

    1. 通过read命令实现用户输入
    #! /bin/bash
    #Get the sum of numbers that the user input
    
    echo "Pls input the first num and press the 'Enter' to continue !"
    read x
    echo "Pls input the second num and press the 'Enter' to continue !"
    read y
    sum=$[$x+$y]
    echo "The sum is $sum"
    
    image.png

  • 参数

    1. shell脚本在运行时,后面可以跟预设变量
    2. 预设变量的值通过 $数字 获取,其中安装顺序依次为 $1 $2 ...$9
    3. 位置变量最多到 $9 ,而预设变量是无限的
    4. 符号 $0 代表脚本本身的名字
    #! /bin/bash
    
    echo "\$0=$0"
    echo "\$1=$1"
    echo "\$2=$2"
    
    image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容