shell 数组操作

时间:2019-10-17
本文章向大家介绍shell 数组操作,主要包括shell 数组操作使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

不像Python那样方便,需要先定义一个变量,用来当数组下标;如下:

c=0
for file in `ls $dir`
do
  filelist[$c]=$file
  ((c++))
done

如果想读取数组内容,可以使用for循环:

for image_name in ${filelist[@]}
do
  if [[ ${image_name} =~ 'tar' ]]
  then
    docker load < $image_name
  fi
done

引用自菜鸟教程

$* 与 $@ 区别:

  • 相同点:都是引用所有参数。
  • 不同点:只有在双引号中体现出来。假设在脚本运行时写了三个参数 1、2、3,,则 " * " 等价于 "1 2 3"(传递了一个参数),而 "@" 等价于 "1" "2" "3"(传递了三个参数)。

    #!/bin/bash
    # author:菜鸟教程
    # url:www.runoob.com

    echo "-- $* 演示 ---"
    for i in "$*"; do
    echo $i
    done

    echo "-- $@ 演示 ---"
    for i in "$@"; do
    echo $i
    done

执行脚本,输出结果如下所示:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
-- $* 演示 ---
1 2 3
-- $@ 演示 ---
1
2
3

原文地址:https://www.cnblogs.com/wswang/p/11692301.html