Shell脚本学习

变量类型

Bash脚本的变量可以细分为以下三个类型:

  • 局部变量 :局部变量在脚本或命令中定义,仅在当前 shell 实例中有效,其他 shell启动的程序不能访问局部变量;

  • 环境变量 :所有的程序,包括 shell 启动的程序,都能访问环境变量,有些程序需要环境变量来保证其正常运行。

    必要的时候 shell 脚本也可以定义环境变量;

  • shell 变量:shell 变量是由 shell 程序设置的特殊变量。 shell 变量中有一部分是环境变量,有一部分是局部变量。

定义变量和使用变量

在定义和使用变量时,应遵循如下描述: (1) 定义变量 name=value 需要注意,等号两侧不能有空格; (2) 使用变量: echo $name 或 echo ${name} (3) 定义局部变量: local name="test" (4) 定义只读变量: readonly name (5) 删除变量: unset name 。

Bash 字符串

在Bash 中,字符串可以是单引号或双引号,二者的区别如下:

  • 单引号:单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的;单引号字 串中不能出现单独一个的单引号,但可以成对出现,作为字符串拼接使用;

  • 双引号:双引号里可以有变量且可以出现转义字符。

Bash 中的参数

在Bash 中使用参数时,具体定义如下:

  • Bash 中的参数按照数字顺序定义;

  • Bash 脚本内获取参数的格式为:$n 。

几个特殊参数 Bash中除了正常的顺序参数以外,还有一些特殊参数:

  • $0:脚本文件名;

  • $#:传递到脚本的参数的个数

  • $*:以一个单字符串显示所有向脚本传递的参数。

流程控制

if else-if else

格式

if condition1
then
command1
elif condition2
then
command2
else
commandN
fi

例:

#!/bin/bash
​
score=$1
​
if (( score >= 90 )); then
    echo "优秀"
elif (( score >= 80 )); then
    echo "良好"
elif (( score >= 60 )); then
    echo "及格"
else
    echo "不及格"
fi
​
# 输出
<<EOF
[root@VM-16-8-centos shellSet]# ./score.sh 60
及格
[root@VM-16-8-centos shellSet]# ./score.sh 61
及格
[root@VM-16-8-centos shellSet]# ./score.sh 81
良好
[root@VM-16-8-centos shellSet]# ./score.sh 90
优秀
EOF
for 循环

格式

for variable in list
do
    # 在循环中执行的代码块
done

例:

#!/bin/bash
​
fruits=("apple" "banana" "orange" "grape")
# 数组迭代
for fruit in "${fruits[@]}"
do
    echo "$fruit"
done
# 数字范围迭代
for num in {1..5}
do
    echo "$num"
done
​
# 输出
<<EOF
[root@VM-16-8-centos shellSet]# ./for.sh
apple
banana
orange
grape
1
2
3
4
5
EOF
While 循环

格式

while condition
do
    # 执行的命令
done

例:

#!/bin/bash
​
counter=1
# while 循环检查 counter 是否小于或等于 5。如果是,则输出 counter 的值,并将 counter 的值递增 1。循环将继续执行,直到 counter 的值大于 5。
while [ $counter -le 5 ]
do
    echo $counter
    counter=$((counter + 1))
done
# 注意,在 while 循环中,condition 部分必须返回一个布尔值,通常使用比较运算符(如 -lt、-le、-gt、-ge、-eq、-ne)来比较变量的值。
​
# 输出
<<EOF
[root@VM-16-8-centos shellSet]# ./while.sh
1
2
3
4
5
EOF
until循环

注: until 循环会在条件为假时执行循环体

格式

until condition
do
执行的命令
done

例:

#!/bin/bash
​
counter=1
# until 循环检查 counter 是否大于 5。如果不是,则输出 counter 的值,并将 counter 的值递增 1。循环将继续执行,直到 counter 的值大于 5。
until [ $counter -gt 5 ]
do
    echo $counter
    counter=$((counter + 1))
done
​
# 输出
<<EOF
[root@VM-16-8-centos shellSet]# ./until.sh
1
2
3
4
5
EOF
跳出循环

在循环过程中,如果需要跳出循环,则可以考虑使用 break 或 continue

  • 跳出循环使用 break

  • 跳过当前循环使用 continue

函数

格式
function_name() {
    # 函数体,包含一系列命令
    # 可以使用参数和局部变量
    # 可以使用 return 语句返回值(可选)
}
​
# 调用函数
function_name

例:

# 定义函数
say_hello() {
    local name=$1
    echo "Hello, $name!"
}
​
# 调用函数
say_hello $1
​
# 输出
<<EOF
[root@VM-16-8-centos shellSet]# ./function.sh World
Hello, World!
EOF