shell基础知识2--数组、流程控制、循环、条件判断

本文详细介绍了Shell编程中的基础知识,包括数组的创建与操作、各种运算符的使用、条件判断的语法及其应用,以及流程控制结构如if、case和for、while循环的实例解析。通过这些内容,读者可以更好地掌握Shell脚本编程的基本技巧。
摘要由CSDN通过智能技术生成
1、shell中的数组

1.创建空数组

[root@tom shell]# arr=()

单个赋值

[root@tom shell]# arr[0]=1
[root@tom shell]# arr[1]=2

输出

[root@tom shell]# echo ${arr[0]}
[root@tom shell]# echo ${arr[1]}

2.创建非空数组,并输出

[root@tom shell]# arr1=(1 2 3 4 5)
[root@tom shell]# echo ${arr1[0]}
1

3.输出
输出某个元素,根据索引输出

[root@tom shell]# echo ${arr[0]}
1

输出所有的元素
echo ${arr[*]}/echo ${arr[@]}

[root@tom shell]# echo ${arr[*]}
1 2
[root@tom shell]# echo ${arr[@]}
1 2

获取数组的长度
echo ${#arr[*]}/echo ${#arr[@]}

[root@tom shell]# echo ${#arr[*]}
2
[root@tom shell]# echo ${#arr[@]}
2

遍历数组/数组的循环迭代

[root@tom shell]# vim shell_arr.sh 

#!/bin/bash
:<<!
迭代数组
!

arr1=(a b c d 'abcd')

for i in ${arr1[*]}
do
        echo $i
done


[root@tom shell]# chmod +x shell_arr.sh 
[root@tom shell]# ./shell_arr.sh 
a
b
c
d
abcd

2、shell运算符

常用的运算符

运算符 描述
+
-
*
/
% 取余

运算的方式有2种
第一种

$(($a+$b))/$[$a+$b]

中间没有空格

[root@tom shell]# a=1
[root@tom shell]# c=2
[root@tom shell]# echo $[$a+$c]
3
[root@tom shell]# echo $[$a-$c]
-1
[root@tom shell]# echo $[$a*$c]
2
[root@tom shell]# echo $[$a/$c]
0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值