bash, zsh : declare [*] (oh my)

时光总嘲笑我的痴心妄想 提交于 2019-12-10 17:10:22

问题


I'm working with a bash script that has the following syntax

$ declare -a THIS[*]

This seems to be illegal in zsh (I get a "no matches found: THIS[*]" error). Can anyone help me translate this to zsh?

Also - what does the [*] syntax mean? (I know we're declaring an array, but why the [*]?)

update

To provide an example of where the code is used, and explain how it is valid - I've copied a few lines from Eric Engstrom's post on password free ssh

declare -a SSSHA_KEYS[*]

# --- PARSE ARGS --- #
sssha_parse_args() {
  local OPTIND=1
  while getopts "xe:k:t:" OPT; do
    #echo "$OPT $OPTARG $OPTIND"
    case $OPT in
      t) SSSHA_ARGS="-t $OPTARG" ;;
      e) SSSHA_ENV="$OPTARG" ;;
      k) [ -f "${OPTARG}" ] && SSSHA_KEYS[${#SSSHA_KEYS[*]}]="$OPTARG" ;;
      x) SSSHA_STOP_ON_EXIT=$OPT
    esac
  done
  shift $(($OPTIND - 1))

  # set default key, if none specified
  if [ -z "${SSSHA_KEYS[*]}" ]; then
    for key in $HOME/.ssh/id_[rd]sa; do
      [ -f "$key" ] && SSSHA_KEYS[${#SSSHA_KEYS[*]}]="$key"
    done
  fi
}

I believe the [*] is being used as some kind of dynamic iterator (as we don't know how many items it will have later). I'd just like to know of the equivalent declaration in zsh!


回答1:


Only Bash has declare. The kshes and zsh have typeset. That code is nonsensical in all of them, and since shells disagree about the parsing of the arguments to declaration commands like declare and typeset (with Bash in particular, -a alters parsing in a specific way), it's going to do a different unpredictable, potentially dangerous thing in each.

Specifically how Bash is interpreting this - from the manpage:

declare -a name[subscript] is also accepted; the subscript is ignored.

So since it's unquoted - if there's a file in the current directory named THIS* then Bash would throw an illegal name error due to the pathname expansion. Otherwise it will just create an empty array named "THIS".

What [*] means depends upon context. Unquoted in an ordinary command evaluation context, it's a character class matching only literal asterisks. If used in a parameter expansion following an array name, it expands all elements of the array to a single word separated by the first character of IFS.

declare in bash declares variables, returns their values, sets attributes, and affects function scope. See: http://wiki.bash-hackers.org/commands/builtin/declare

edit: Given the example that's now in the question, in bash the behavior is as described above. The [*] should be deleted from the declare. That code has a number of other issues such as attempting to put arguments into strings, using all-caps variable names, and using [ instead of [[ in a script that's clearly not intended to run on a minimal POSIX sh.



来源:https://stackoverflow.com/questions/10194861/bash-zsh-declare-oh-my

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!