Bash - 数组作为参数

标签 bash

我在使用数组作为函数参数时遇到问题。

#!/usr/bin/env bash

function array_param
{
  local ARRAY_s; local ARRAY_t; local OPTIND

  while getopts 's:t:' opt ; do
    case "$opt" in
      s) ARRAY_s=$OPTARG;;
      t) ARRAY_t=$OPTARG;;      
    esac
  done
  shift $((OPTIND-1))
  echo "ARRAY_s=${ARRAY_s[@]}; ARRAY_t=${ARRAY_t[@]}"
}

array_s=(100 200 300)
array_t=(0 10 3585)

array_param -s ${array_s} -t ${array_t}

为什么只有第一个元素分配给变量 ARRAY_s 和 ARRAY_t?

Result: ARRAY_s=100; ARRAY_t=0

最佳答案

稍微修改函数(变量使用小写字母,并使用数组语义)

array_param() {
    local l_array_s l_array_t OPTIND

    while getopts 's:t:' opt ; do
        case "$opt" in
        s) l_array_s+=( "$OPTARG" ) ;;
        t) l_array_t+=( "$OPTARG" ) ;;
        esac
    done
    shift $((OPTIND-1))
    echo "l_array_s=${l_array_s[*]}; l_array_t=${l_array_t[*]}"
}

可以调用

array_param "${array_s[@]/#/-s}" "${array_t[@]/#/-t}"
  • ${array_s[@]/#/-s} 表示法是 bash 特有的,# 匹配字符串的开头并被替换为 -s 数组中的每个元素。

跟随 printf 理解参数是如何传递的

printf "<%s> " "${array_s[@]/#/-s}" "${array_t[@]/#/-t}"

也比较

printf "<%s> " "${array_s}"
printf "<%s> " "${array_s[@]}"
printf "<%s> " "${array_s[*]}"

关于Bash - 数组作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48227092/

相关文章:

linux - 使用 printf 如何转义 shell 脚本中的特殊字符?

arrays - bash脚本在expect代码中增加数组索引

linux - diff 命令忽略新目录中的新文件

arrays - 有没有办法在 Bash 中将一个字符串数组拆分为多个其他数组?

linux - 在 shell 中以其他用户身份运行时无法初始化变量

MySQL命令行执行

bash - 使用 FFMPEG 自动分割文件

terminal - 在 Mac OS X 中运行终端时如何找出别名(在 bash 意义上)的定义位置

bash - 使用 bash 自动化点文件

bash - 启动另一个应用程序的脚本将在退出时将其关闭