当前位置: 首页 > news >正文

香橙派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

相关文章:

  • 定时线程池失效问题引发的思考
  • 前端导入Excel表格
  • 提升系统稳定性和可靠性的特殊线程(看门狗线程)
  • CppCon 2014 学习:Lightning Talk: Writing a Python Interpreter for Fun and Profit
  • 浮点数的位级表示转变为二进制表示
  • 数组-差分数组抽象版
  • 【Redis】笔记|第7节|大厂生产级Redis高并发分布式锁实战(二)
  • 风机巡检方案艰难之路
  • 基于TI DSP控制的光伏逆变器最大功率跟踪mppt
  • 【Zephyr 系列 5】定时器与低功耗控制:打造省电高效的嵌入式系统
  • Windows 下部署 SUNA 项目:虚拟环境尝试与最终方案
  • 数据生命线 - MySQL 备份与恢复策略详解
  • ADI硬件笔试面试题型解析上
  • VueScan:全能扫描,高清输出
  • STM32学习之WWDG(原理+实操)
  • 适合自己的记单词方式
  • 中英混合编码解码全解析
  • C++实现汉诺塔游戏用户交互
  • 【笔记】用命令手动下载并安装 tokenizers 库.whl文件(Python 3.12+)
  • 动态规划(2)
  • 深圳东莞网站开发/成都门户网站建设
  • 门户网站建设和运行保证的磋商文件/seo推广哪家公司好
  • 开发区网站制作公司/外链网盘网站
  • 苏州市相城区疫情最新消息/seo优化外链平台
  • 手机微网站与微官网/国外网站seo免费
  • 做地产网站哪家好/网络seo是什么