【Shell】菜鸟教程bash学习记录

1 . 通用

  • Bourne Again Shell称为bash
  • #!申明解释器,#!/bin/bash
  • POSIX 可移植操作系统接口Portable Operating System Interface of Unix
  • chmod +x file 添加文件可执行权限
  • 使用变量$
  • 双引号字符串"value is ${num}"
  • #计算字符串长度
  • $string:n:m提取子串
  • 数组用空格分开Array=(1 2 3 4)
  • $Array[@]表示所有数组元素
  • 获取数组长度${#Array[@]}
  • #表注释
  • 脚本传参$n
  • expr表达式计算
  • expr a + b运算符与数字之间要有空格
  • 乘法\*
  • \n换行
  • \c不换行
  • echo "sss" > file 输出到文件
  • printf
    • %-10s长度为10的字符,-左对齐
    • %d %f
  • test [$a == $b]

2. 运算符

  • 关系运算符(只用于数字)
    • -eq equal
    • -ne not equal
    • -lt less than
    • -gt great than
    • -le less or equal
    • -ge great or equal
  • 布尔运算符
    • ! not
    • -o or
    • -a and
  • 逻辑运算符
    • && 逻辑与
    • || 逻辑或
  • 字符串运算符
    • =
    • !=
    • -z 长度是否为零
    • $ 是否为空
  • 文件测试运算符
    • -d
    • -f
    • -e
    • -r -w -x

3. 流程控制语句

  • if ... then ... else ... fi
# 判断语句
if [ $a == $b ]
    then
        echo 'true'
fi
  • for ... in ... do... done
# 循环语句
for a in ${array[@]}
do
    echo $a
done
  • while ... do ... done
  • until ... do ... done
  • case...in...)...;;...esac
  • function(){...}
  • 函数返回值,调用函数后用$?获取

4. 输入输出重定向

  • command > file 终端不再有输出,重定向的含义就是本来输出到终端的被重新定向输出到文件
  • command >> file 追加到文件末尾
  • command < file
  • 每个linux命令运行时都会打开三个文件:stdin stdout stderr
  • >/dev/null禁止输出

5. 文件包含

  • . filename 引入文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章