Bash脚本学习 - 条件句、数组、for循环,函数

1. 条件测试

  • [ 和 ] 是一个用于执行条件测试的命令。它们必须用空格分隔开,并且在 [ 后面和 ] 前面必须有空格。
  • -eq 是一个比较运算符,表示等于(equal)。它用于比较两个值是否相等。

2. 条件句

ifelseifelse.sh 文件中,

bash 复制代码
#!/bin/bash

if [ ${1,,} = herbert ]; then
        echo "Oh, you're the boss here. Welcome!"
elif [ ${1,,} = help ]; then
        echo "Just enter your username, duh!"
else
        echo "I don't know who you are. But you're not the boss of me!"
fi

3. Case statement

在 admin.sh文件中,

bash 复制代码
#!/bin/bash

case ${1,,} in
        herbert | administrator)
                echo "Hello, you're the boss here!"
                ;;
        help)
                echo "Just enter your username!"
                ;;
        *)
                echo "Hello there. You're not the boss of me. Enter a valid username!"
esac

4. 数组

  • 这个例子展示了如何创建一个数组。
  • 如何打印数组的第一个元素。
  • 如何打印整个数组。
  • 如何打印数组某个位置的元素。

5. for 循环

bash 复制代码
for item in ${MY_FIRST_LIST[@]}; do echo -n $item | wc -c; done

输出为:

3

3

5

4

4

  • for item in {MY_FIRST_LIST\[@\]}; do:这是一个for循环的开始,它将遍历名为MY_FIRST_LIST的数组中的所有元素。item表示当前遍历到的数组元素。

  • echo -n $item:这部分命令用于打印(显示)当前数组元素的值,但-n选项表示不要在末尾添加换行符。这意味着它会把元素值输出在同一行。

  • |:这是管道符号,它将前一个命令的输出传递给后一个命令作为输入。

  • wc -c:这部分命令使用wc命令来统计字符数(字节数)。-c选项告诉wc只统计字符数,而不是单词数或行数。

  • ";":这是命令分隔符,它用于将多个命令放在同一行。

  • done:这是for循环的结束标记,表示循环体的结束。

6. 函数

写一个显示计算机的运行时间和启动时间的脚本。

在firstfunction.sh中,

bash 复制代码
#!/bin/bash

showuptime(){
        local up=$(uptime -p | cut -c4-)
        local since=$(uptime -s)
        cat << EOF
-----
This machine has been up for ${up}
It has been running since ${since}
-----
EOF
}
showuptime

输出为:

  • uptime -p命令用于获取计算机的运行时间,然后使用cut -c4-命令将字符串的前三个字符(通常是"up ")去掉,以得到纯粹的运行时间。
  • uptime -s命令用于获取计算机的启动时间。
  • cat << EOF:这是一个Here Document结构,它用于创建一个包含多行文本的块。这里的EOF表示文本块的结束标记。
  • showuptime:这一行表示调用定义的showuptime函数。

7. 函数和位置自变量

functionposargu.sh 文件中,

bash 复制代码
#!/bin/bash

showname(){
        echo hello $1
}
showname Herbert

8. 函数和条件句

functionposargu.sh 文件中,

bash 复制代码
#!/bin/bash

showname(){
        echo hello $1
        if [ ${1,,} = herbert ]; then
                return 0
        else
                return 1
        fi
}
showname $1
if [ $? = 1 ]; then
        echo "Someone unknown called the function!"
fi
  • 条件句中,如果输入和位置变量为 herbert ,返回0;否则,返回1。
相关推荐
难以触及的高度2 天前
source ~/.bash_profile有什么用
开发语言·bash
Licky133 天前
Centos中dnf和yum区别对比
linux·运维·架构·centos·bash
fengyehongWorld3 天前
Linux bash脚本本地开发环境(Git Bash)配置
linux·bash
异构算力老群群3 天前
从零到一:构建你的第一个AI项目(实战教程)
人工智能·学习·bash·gnu
悟空不是猴子4 天前
VS Code终端命令执行后老是出现 __vsc_prompt_cmd_original: command not found
windows·vscode·prompt·bash
EterNity_TiMe_4 天前
【Linux进程】Linux Shell编程实战:构建简易脚本示例与技巧详解
linux·运维·服务器·学习·centos·bash
the丶only5 天前
获取zabbix API 监控数据shell脚本,自动日常巡检服务器信息、并发送指定群组
linux·运维·服务器·自动化·bash·zabbix
秋刀prince7 天前
简单说说关于shell中zsh和bash的选择
bash
promise5247 天前
Linux cat命令详解使用:高效文本内容管理
linux·运维·服务器·后端·bash
Mostcow8 天前
Linux运维_Bash脚本_源码编译Moby(Docker-CE)-20240803
linux·docker·bash