今日学习基本的linux 的一些 bash 脚本
ssh : orangepi@本地ip
密码 : orangepi操作系统发行版: 基于 Ubuntu 20.04.6 LTS(Focal Fossa)的定制版本,专门为 Orange Pi 设备优化。PRETTY_NAME="Orange Pi 1.0.6 Focal"
目录
终端打印输出:
先从最简单的打印输出开始
#!/bin/bash # 一个简单的打印脚本 echo "Hello, World!"
我是在windows系统的txt文本文件写了这行代码,然后改后缀为.sh,
然后拖到linux目录的,这会遇到UTF-8编码的格式问题,这里讲下怎么解决
先尝试能不能正常打开运行脚本:
导航脚本目录:
cd /home/orangepi/Bash_test
给予脚本权限:
chmod +777 hello.sh
运行脚本:
./hello.sh
发现没有转换掉windows风格的换行符,导致无法运行:
使用 dos2unix
工具
安装:
sudo apt-get install dos2unix
启动转换:
dos2unix hello.sh
成功运行:
以下的测试基本都要基于cd 到了脚本文件的目录下才能进行!
变量使用+用户输入:
#!/bin/bash name="Alice" age=25 # 获取用户输入 echo "Please enter your name:" read name echo "Please enter your age:" read age echo "your name is $name and you are $age years old."
条件判断:
#!/bin/bash # 条件判断示例 echo "Enter a number:" read num #if 语句用于条件判断。-gt 表示大于,-eq 表示等于,-lt 表示小于。注意条件判断语句两边要有空格。 if [ $num -gt 10 ]; then echo "The number is greater than 10." elif [ $num -eq 10 ]; then echo "The number is equal to 10." else echo "The number is less than 10." fi
for循环:
#!/bin/bash # for 循环示例 for i in {1..5}; do echo "Number: $i" done
while循环:
#!/bin/bash # while 循环示例 count=1 #-le 表示“小于或等于” #-gt 表示大于,-eq 表示等于,-lt 表示小于 while [ $count -le 5 ]; do echo "Count: $count" count=$((count + 1)) done
数组:
#!/bin/bash # 数组操作示例 fruits=("apple" "banana" "orange") # 遍历数组 for fruit in "${fruits[@]}"; do echo "Fruit: $fruit" done # 获取数组长度 echo "Number of fruits: ${#fruits[@]}"
函数定义与调用:
#!/bin/bash # 函数定义与调用示例 greet() { echo "Hello, $1!" } greet "Bob"
文件操作:
#!/bin/bash # 文件操作示例 file="example.txt" # 检查文件是否存在 if [ -f "$file" ]; then echo "File $file exists." # 读取文件内容 while IFS= read -r line; do echo "Line: $line" done < "$file" else echo "File $file does not exist." fi
参数处理:
#!/bin/bash # 参数处理示例 echo "Script name: $0" echo "First argument: $1" echo "Second argument: $2" echo "Number of arguments: $#" # 处理所有参数 for arg in "$@"; do echo "Argument: $arg" done