Linux Shell编程基础

1 什么是 Shell?

Shell 是一个命令行解释器,它为用户和操作系统之间提供了一个接口。通过 Shell,用户可以执行命令、启动程序和编写脚本。Bash(Bourne Again SHell)是 Linux 中最常用的 Shell 之一。

2 基础语法

2.1 变量定义

# 字符串
my_string="Hello, World!"
# 数字
num=42
# 数组
array=("apple" "banana" "cherry")
# 字典
declare -A my_dict
my_dict["name"]="Alice"
my_dict["age"]=30

2.2 条件判断

#!/bin/bash

num=5
# 使用 [] 进行测试
if [ $num -gt 0 ]; then
    echo "The number is positive."
else
    echo "The number is not positive."
fi

2.4 循环结构

#!/bin/bash

# 使用for循环
for i in {1..5}; do
    echo "Iteration $i"
done

# 使用while循环
count=1
while [ $count -le 5 ]; do
    echo "Count: $count"
    ((count++))
done

2.5 使用函数

以下展示了如何使用一个带参数和本地变量的函数:

#!/bin/bash

# 定义函数
calculate_area() {
    # 接受第一个参数到某个局部变量
    local width=$1
    # 接受第二个参数到某个局部变量
    local height=$2
    local area=$(($width * $height))
    echo "Area: $area"
}

# 调用函数
calculate_area 5 3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值