参考:https://linuxhint.com/30_bash_script_examples/#t1
    多动手,才能记住,手脑并用才能成长

    第一个linux:

    1. #!/bin/bash
    2. echo "hello"

    给脚本赋予权限:
    chmod +x hello.sh
    执行脚本:
    ./hello.sh

    变量:

    1. #!/bin/bash
    2. ((a=11+11))
    3. echo $a

    这里a是变量,(()) 里面的会自动计算值。
    循环+判断:while+if的用法

    1. #!/bin/bash
    2. a=true
    3. b=1
    4. while [ $a ]
    5. do
    6. echo $b
    7. if [ $b -eq 5 ] ;then
    8. break;
    9. fi
    10. ((b++))
    11. done

    for 循环:

    1. #!/bin/bash
    2. for ((a=10;a>0;a--))
    3. do
    4. echo $a
    5. done
    6. printf "\n"

    输入:(read变量,程序运行到这里会停止 等待用户输入)

    1. #!/bin/bash
    2. echo "enter your name"
    3. read name
    4. echo "hello $name"

    if elif 语句:

    1. #!/bin/bash
    2. echo "enter a number"
    3. read a
    4. if [ $a -eq 1 ];then
    5. echo "1"
    6. elif [ $a -eq 2 ];then
    7. echo "2"
    8. elif [ $a -eq 3 ];then
    9. echo "3"
    10. else
    11. echo "try another"
    12. fi

    case语句:

    1. #!/bin/bash
    2. echo "enter a number"
    3. read a
    4. case $a in
    5. 1)
    6. echo "1" ;;
    7. 2)
    8. echo "2" ;;
    9. 3)
    10. echo "3" ;;
    11. *)
    12. echo "not found"
    13. esac

    for + case 语句如何使用:

    1. #!/bin/bash
    2. for arg in "$@"
    3. do
    4. index=$(echo $arg | cut -f1 -d = )
    5. val=$(echo $arg | cut -f2 -d = )
    6. case $index in
    7. X) x=$val ;;
    8. Y) y=$val ;;
    9. *)
    10. esac
    11. done
    12. ((number=x+y))
    13. echo "the number is $number"

    字符串截取:

    1. #!/bin/bash
    2. Str="Learn Linux from LinuxHint"
    3. subStr=${Str:6:5}
    4. echo $subStr

    ${Str:6:5} 意思是从字符串的 第6位开始(包含第6位,截取长度为5的字符串)

    简单函数:

    1. #!/bin/bash
    2. function F1(){
    3. echo "hello function"
    4. }
    5. F1

    简单函数 如何添加参数:

    1. #!/bin/bash
    2. function sum(){
    3. sum=$(($1 + $2))
    4. echo "$sum"
    5. }
    6. sum 1 22

    获取函数的返回值: sname=$(re)

    1. #!/bin/bash
    2. function re(){
    3. val="$name"
    4. echo "$val"
    5. }
    6. echo "enter your name"
    7. read name
    8. sname=$(re)
    9. echo "$sname"