香橙派3B学习笔记6:基本的Bash脚本学习_UTF-8格式问题
今日学习基本的linux 的一些 bash 脚本
ssh : orangepi@本地ip
密码 : orangepi操作系统发行版: 基于 Ubuntu 20.04.6 LTS(Focal Fossa)的定制版本,专门为 Orange Pi 设备优化。PRETTY_NAME="Orange Pi 1.0.6 Focal"
目录
终端打印输出:
使用 dos2unix 工具
成功运行:
变量使用+用户输入:
条件判断:
for循环:
while循环:
数组:
函数定义与调用:
文件操作:
参数处理:
终端打印输出:
先从最简单的打印输出开始
#!/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/bashname="Alice" age=25# 获取用户输入 echo "Please enter your name:" read name echo "Please enter your age:" read ageecho "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 ]; thenecho "The number is greater than 10." elif [ $num -eq 10 ]; thenecho "The number is equal to 10." elseecho "The number is less than 10." fi
for循环:
#!/bin/bash # for 循环示例 for i in {1..5}; doecho "Number: $i" done
while循环:
#!/bin/bash # while 循环示例 count=1#-le 表示“小于或等于” #-gt 表示大于,-eq 表示等于,-lt 表示小于 while [ $count -le 5 ]; doecho "Count: $count"count=$((count + 1)) done
数组:
#!/bin/bash # 数组操作示例 fruits=("apple" "banana" "orange")# 遍历数组 for fruit in "${fruits[@]}"; doecho "Fruit: $fruit" done# 获取数组长度 echo "Number of fruits: ${#fruits[@]}"
函数定义与调用:
#!/bin/bash # 函数定义与调用示例 greet() {echo "Hello, $1!" }greet "Bob"
文件操作:
#!/bin/bash # 文件操作示例 file="example.txt"# 检查文件是否存在 if [ -f "$file" ]; thenecho "File $file exists."# 读取文件内容while IFS= read -r line; doecho "Line: $line"done < "$file" elseecho "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 "$@"; doecho "Argument: $arg" done