代码之家  ›  专栏  ›  技术社区  ›  joe

如何在shell脚本中处理Perl数组元素?

  •  1
  • joe  · 技术社区  · 16 年前

    例如:

    在Perl中:

    @array = (1,2,3);
    
    system ("/tmp/a.sh @array" ); 
    

    在shell脚本中,如何处理shell脚本中的这个数组?如何处理shell脚本以接收参数,以及如何在shell脚本中使用该数组变量?

    4 回复  |  直到 16 年前
        1
  •  5
  •   Schwern    16 年前

    这是:

    my @array = (1,2,3);   
    system ("/tmp/a.sh @array" );
    

    相当于shell命令:

    /tmp/a.sh 1 2 3
    

    您只需将传递给系统的内容打印出来即可看到这一点:

    print "/tmp/a.sh @array";
    

    a.sh 应该像处理其他shell参数集一样处理它们。

    为了安全起见,您应该绕过shell并将数组作为参数直接传入:

    system "/tmp/a.sh", @array;
    

    @array

    my @array = ("Hello, world", "This is one argument");
    system "./count_args.sh @array";
    system "./count_args.sh", @array;
    

    哪里 count_args.sh 是:

    #!/bin/sh
    
    echo "$# arguments"
    

    你会看到第一个有6个参数,第二个有2个。

    在shell程序中处理参数的简短教程可以找到 here .

        2
  •  2
  •   Dennis Williamson    16 年前

    shell脚本在中接收其参数 $@ :

    #!/bin/sh
    # also works for Bash
    for arg  # "in $@" is implied
    do
        echo "$arg"
    done
    

    在Bash中,还可以使用数组下标或切片来访问它们:

    #!/bin/bash
    echo "${@:2:1}"    # second argument
    args=($@)
    echo "${args[2]}"  # second argument
    echo "${@: -1}"    # last argument
    echo "${@:$#}"     # last argument
    
        3
  •  1
  •   brian d foy    16 年前

    这样地:

       @a=qw/aa bb cc/;
       system("a.sh ".join(' ',@a));
    

    壳内(a.sh):

    #!/bin/sh
    i=1;
    while test "$1"
    do
        echo argument number $i = $1
        shift
        i=`expr $i + 1`
    done
    
        4
  •  -2
  •   brian d foy    16 年前

    my @array = qw(1 2 3);
    
    system("/tmp/a.sh". join(" ", @array));
    

    my @array = qw(1 2 3);
    foreach my $arr (@array) {
         system("/tmp/a.sh $arr");
    }
    
    推荐文章