数组选择的Bash传递参数

时间:2017-06-27 11:50:16

标签: bash

我试图传递第二个参数来获取数组并循环低谷但是我得到了这个错误:${$2[@]}: bad substitution

我的代码是:

/etc/init.d/displaycameras start c1

    #!/bin/bash
    dis1cam1="screen -dmS dis1cam1 sh -c 'omxplayer --avdict rtsp_transport:tcp --win \"0 0 640 428\" rtsp://myvideo --live -n -1'";
    camera_feeds=('c1=(dis1cam1 dis1cam2 dis1cam3 dis1cam4 dis1cam5 dis1cam6 dis1cam8 dis1cam9)' 'c2=(dis2cam1 dis2cam2 dis2cam3 dis2cam4)')
    for elt in "${camera_feeds[@]}";do eval $elt;done

    # Start displaying camera feeds
    case "$1" in
    start)
    for i in "${$2[@]}"
    do
    eval eval '$'$i
    done
    echo "Camera Display 1 Started"
    ;;

有没有办法传递第二个参数来调用c2 set?

以这种方式工作得很完美:

        #!/bin/bash
 dis1cam1="screen -dmS dis1cam1 sh -c 'omxplayer --avdict rtsp_transport:tcp --win \"0 0 640 428\" rtsp://myvideo --live -n -1'";

        camera_feeds=('c1=(dis1cam1 dis1cam2 dis1cam3 dis1cam4 dis1cam5 dis1cam6 dis1cam8 dis1cam9)' 'c2=(dis2cam1 dis2cam2 dis2cam3 dis2cam4)')
        for elt in "${camera_feeds[@]}";do eval $elt;done

        # Start displaying camera feeds
        case "$1" in
        start)
        for i in "${c1[@]}"
        do
        eval eval '$'$i
        done
        echo "Camera Display 1 Started"
        ;;

1 个答案:

答案 0 :(得分:2)

强烈建议以不同的方式实施。

#!/usr/bin/env bash

die() { echo "$*" >&2; exit 1; }
[[ $BASH_VERSION = [0-3]* ]] && die "Bash 4.3 or newer needed"
[[ $BASH_VERSION = 4.[0-2].* ]] && die "Bash 4.3 or newer needed"

dis1cam1() { : "code to start camera dis1cam1 here"; )
dis1cam2() { : "code to start camera dis1cam2 here"; )
# ...etc...

camera_feeds__c1=(dis1cam1 dis1cam2 dis1cam3 dis1cam4 dis1cam5 dis1cam6 dis1cam8 dis1cam9)
camera_feeds__c2=(dis2cam1 dis2cam2 dis2cam3 dis2cam4)

# here, we're showing the iterate-over-all-feeds case
# you can just set var=camera_feeds__c1 yourself if you prefer
for var in "${!camera_feeds__@}"; do  # var will be camera_feeds__c1 or camera_feeds__c2
  feed_name=${var#camera_feeds__}     # feed_name will be "c1" or "c2"
  declare -n camera_feeds=$var
  for i in "${camera_feeds[@]}"; do
    echo "Starting $i in feed $feed_name" >&2
    "$i" # look up and run code in variable named in $i
  done
  unset -n camera_feeds
done
  • "${camera_feeds__@}"扩展为名称以camera_feeds__开头的shell变量列表;因此,这是我们两个数组的名称。
  • declare -n camera_feeds=$var然后使camera_feeds为当前正在迭代的数组的别名,以便for i in "${camera_feeds[@]}"遍历该数组。
  • unset -n camera_feeds清除此关联。