现在的位置: 首页 > 程序人生 > Linux > 正文
教你使用shell数组
2013年07月11日 Linux, shell, 程序人生 ⁄ 共 537字 评论数 11 ⁄ 被围观 86,920 views+

数组的使用,需要掌握

1、对数组进行赋值

2、通过下标访问数组元素

3、循环遍历所有的元素

代码如下:

#!/bin/bash

a="39"
b="5"
c="36"
d="12"
e="9"
f="35"
# 对数组进行赋值
values=("$a" "$b" "$c" "$d" "$e" "$f")
#values=(39 5 36 12 9 35)

# 获取数组的长度
numvalues=${#values[@]}
# 循环输出数组的元素
for (( i=0; i < numvalues; i++ ))
do
    echo -ne "${values[$i]}\t"
done
echo ""

# 冒泡法排序
for (( i=0; i < numvalues; i++ ))
do
    lowest=$i
    for (( j=i+1; j < numvalues; j++ ))
    do
        if [ ${values[j]} -le ${values[lowest]} ]; then
            lowest=$j
        fi
    done
    temp=${values[i]}
    values[i]=${values[lowest]}
    values[lowest]=$temp
done

for (( i=0; i < numvalues; i++ ))
do
    echo -ne "${values[$i]}\t"
done
echo ""

同时,代码中还给出了对数组元素的冒泡法排序。

原创文章,转载请注明: 转载自成长的企鹅

本文链接地址: 教你使用shell数组

关于我:成长的企鹅简介

【上篇】 【下篇】

目前有 11 条留言 其中:访客:11 条, 博主:0 条

  1. MosesTak : 2018年04月23日23:27:49  -49楼 @回复 回复

    I like everything you post. You’ve done great job

  2. MosesTak : 2018年04月24日19:03:07  -48楼 @回复 回复

    Thanks for sharing, I always learn interesting things from your posts.

  3. cialis prices : 2018年04月30日00:07:24  -47楼 @回复 回复

    You reported this very well.

  4. Briannup : 2018年05月08日06:01:28  -46楼 @回复 回复

    Thank you for your impressive blog. It was very helpful. I am so glad I came across this.

  5. Briannup : 2018年05月08日19:38:49  -45楼 @回复 回复

    Thank you for sharing, I always discover interesting things from your posts.

  6. Briannup : 2018年05月08日22:37:57  -44楼 @回复 回复

    Many thanks for helping people find the info they need. Great stuff as usual. Keep up the good work!!!

  7. Bali : 2018年05月17日09:10:38  -43楼 @回复 回复

    I’m amazed, I must say. Seldom do I come across a blog that’s equally
    educative and entertaining, and without a doubt, you have hit the nail on the head.
    The issue is an issue that not enough people are speaking intelligently
    about. I’m very happy I found this in my hunt for something regarding this.

  8. Thomasled : 2018年05月19日02:08:30  -42楼 @回复 回复

    it’s my first time visiting your blog and I am very interested. Many thanks for sharing and keep up 😉

  9. gwak : 2018年05月24日18:35:14  -41楼 @回复 回复

    I have read so many posts regarding the blogger lovers however this paragraph is genuinely a fastidious post,
    keep it up.

  10. BrianCab : 2018年06月22日01:23:02  -40楼 @回复 回复

    This is my first time visiting your site and I am very interested. Many thanks for sharing and keep up 😉

  11. BrianCab : 2018年06月22日16:52:31  -39楼 @回复 回复

    Thank you for helping people get the info they need. Great stuff as usual. Keep up the good work!!!

给我留言

留言无头像?


×