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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NULL指向我

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值