Shell 脚本笔记

本文最后更新于:2022年8月29日 凌晨

字符串

定义字符串

string="abcdef"

截取字符串 - 根据索引和长度

# 从左往右
${string:start:length}
# 例如
${string:2:2}  # 结果为"cd"
# 省略长度则截取到字符串末尾
${string:2}  # 结果为"cdef"

# 从右往左
${string:0-start:length}
# 例如
${string:0-2}  # 结果为"ef"

截取字符串 - 根据子字符串

# 使用"#"截取指定子字符串右侧的所有字符
${string#*chars}
# 例如
${string#*cd}  # 结果为"ef""*"为通配符

# 使用"%"截取指定子字符串左侧的所有字符
${string%chars*}
# 例如
${string%cd*}  # 结果为"ab""*"为通配符

拼接字符串

str1="abc"
str2="def"
str=${str1}${str2}  # 结果为"abcdef"
str1=${str1}${str2}  # 追加,结果为"abcdef"

数组

定义数组很简单,总之就是圆括号括起来,元素之间用空格或者换行间隔就行。需要注意 shell 脚本中赋值符号”=“前后不能加空格。

list=(item1 item2 ... item3)

获取指定元素

${list[index]}

添加元素

# 在列表list索引3的位置插入或覆盖为字符串"abc"
list[3]="abc"

获取数组长度

${#list[@]}
${#list[*]}

获取数组所有元素

${list[@]}
${list[*]}

循环

带索引的循环

# 格式一
for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

# 格式二
for var in item1 item2 ... itemN; do
    command1
    command2
    ...
    commandN
done

实际编写脚本的时候,一般都不会把所有的遍历的情况都列出来,所以更多的场景我们需要自动的遍历一个数组。

遍历数组中所有元素

for var in ${list[@]}; do
    echo ${var}
done

用索引遍历数组所有元素

for i in "${!list[@]}"; do
    echo ${list[i]}
done

无限循环

while true; do
    command1
    command2
    ...
    commandN
done

带次数的无限循环

index=1
while true; do
    command1
    command2
    ...
    commandN
    index=$((index + 1))
done

将命令后台运行

此前我也纠结过nohup&都有什么作用,但后来发现其实基本需要这种操作的大部分场景都得两者搭配使用。

nohup command &

按行读文件

while read line; do
    echo ${line}
done < file

将字符串作为命令执行

总之就是 eval 命令,后面跟要执行的命令的字符串就行。

eval command_string

Shell 脚本笔记
https://mxy493.xyz/2022082758002/
作者
mxy
发布于
2022年8月27日
许可协议