shell脚本

  • 变量名和等号之间不能有空格
  • 推荐给所有变量加上花括号,这是个好的编程习惯
  • 字符串可以用单引号,也可以用双引号,也可以不用引号。
  • 单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的
  • 单引号字串中不能出现单独一个的单引号(对单引号使用转义符后也不行),但可成对出现,作为字符串拼接使用。
  • 双引号里可以有变量
  • 双引号里可以出现转义字符
  • 拼接字符串
your_name="runoob"
# 使用双引号拼接
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting  $greeting_1
# 使用单引号拼接
greeting_2='hello, '$your_name' !'
greeting_3='hello, ${your_name} !'
echo $greeting_2  $greeting_3
  • 获取字符串长度
string="abcd"
echo ${#string} #输出 4
  • 子串
string="runoob is a great site"
echo ${string:1:4} # 输出 unoo
  • 查找子串
string="runoob is a great site"
echo `expr index "$string" io`  # 输出 4
  • 定义数组
# 在 Shell 中,用括号来表示数组,数组元素用"空格"符号分割开。定义数组的一般形式为:

数组名=(值1 值2 ... 值n)
  • 读取数组元素
${数组名[下标]}
  • 读取数组所有元素
echo ${array_name[@]}
  • 数组元素长度/数组长度
# 取得数组元素的个数
length=${#array_name[@]}
# 或者
length=${#array_name[*]}
# 取得数组单个元素的长度
lengthn=${#array_name[n]}
  • 脚本参数
    我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n 代表一个数字,1 为执行脚本的第一个参数,2 为执行脚本的第二个参数,以此类推…… $0为执行的文件名

  • 表达式和运算符之间要有空格,例如 2+2 是不对的,必须写成 2 + 2
  • 完整的表达式要被 ` ` 包含
  • echo使用-e开启转义,\n表示换行
  • 原样输出字符串,不进行转义或取变量(用单引号)
echo '$name\"'
$name\" #输出
  • if-else结构
if condition
then
    command1 
    command2
    ...
    commandN 
fi # 必须写

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi # 必须写
  • for结构
for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done
posted @ 2022-02-20 22:25  ijpq  阅读(17)  评论(0编辑  收藏  举报