shell脚本学习——数组的练习

1 使用循环批量输出数组的元素

#!/bin/bash
#使用循环批量输出数组的元素
array=(a b c d e)
for ((i=0;i<${#array[@]};i++))	#从数组的第一个下标0开始,循环数组的所有下标
do
	echo ${array[i]}	#打印数组元素
done

在这里插入图片描述

2 通过竖向列举方法定义数组元素并批量打印

#!/bin/bash
#通过竖向列举方法定义数组元素并批量打印
array=(
westos
redhat
python
linux
)

for ((i=0;i<${#array[@]};i++))
do
echo "This is NO.$i,then content is ${array[i]}"
done
echo ====================================
echo "array lenth:${#array[@]}"

在这里插入图片描述

3 将命令结果作为数组元素定义并打印

#!/bin/bash
#将命令结果作为数组元素定义并打印
dir=($(ls /array))

for ((i=0;i<${#dir[*]};i++))
do
	echo "This is NO.$i,filename is ${dir[$i]}"
done

在这里插入图片描述

4 利用bash for 循环打印下面这句话中字母数不大于6的单词

#!/bin/bash
#利用bash for 循环打印下面这句话中字母数不大于6的单词
# May there be enough clouds in your life to make a beautiful sunset

array=(May there be enough clouds in your life to make a beautiful sunset
)
for ((i=0;i<${#array[@]};i++))
do
	if [ ${#array[$i]} -le 6 ]
	then
		echo ${array[$i]}
	fi
done

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Shell脚本可以使用多种方式来循环遍历数组。 一种常见的方式是使用while循环,通过设置一个计数变量来遍历数组。代码如下所示: ``` i=0 while [ $i -lt ${#array[@]} ] do echo ${array[$i]} let i++ done ``` 这段代码中,我们使用变量`i`来表示数组的下标,当`i`小于数组长度时,进入循环体。在循环体中,通过`${array[$i]}`来获取数组的元素,并打印出来。 另一种常见的方式是使用for循环来遍历数组。代码如下所示: ``` for ((i=0; i<${#array[@}; i++)) do echo ${array[i]} done ``` 在这段代码中,我们使用`$i`作为循环的计数变量,通过设置初始值为0、循环条件为`i<${#array[@]}`、每次循环后对`i`进行自增操作,来遍历数组。通过`${array[i]}`来获取数组的元素,并打印出来。 还有一种方式是使用`for ... in`语句来遍历数组。代码如下所示: ``` for i in "${!array[@]}" do echo ${array[$i]} done ``` 在这段代码中,`"${!array[@]}"`会生成数组的所有下标,然后使用`for ... in`循环遍历这些下标。在循环体中,通过`${array[$i]}`来获取数组的元素,并打印出来。 以上是三种常见的Shell脚本循环遍历数组的方式,你可以根据自己的需求选择其中一种方式来使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Shell 数组遍历的3种方法](https://blog.csdn.net/lovedingd/article/details/126310157)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值