1

I was trying to set up some alias command and function for gcloud. I have written below function and running it in zsh in mac. It runs fine when I pass c and i as individual arguments but not when I pass it is ci. However, if you see below translation is same.

gcp() {
    local -A translation=(
        [c]=compute
        [i]=instances        
        [ci]="compute instances"
    )
    stg="stg-proj-12911"
    tst="tst-proj-1797"
    prd="prd-proj-817"
    
 
    local -a args
    for arg in "$@"; do
        if [[ -v "translation[$arg]" ]]; then
            args+=("${translation[$arg]}")
        elif [[ -v ${arg} ]]; then
           echo "project $arg has been set"
           #args+="--project=eval echo \$$arg"
           args+="--project=${(e)arg:+\$$arg}"
            #statements
        else
            echo "$arg"
            args+=("$arg")
        fi
    done
    echo  "${args[@]}"
    gcloud "${args[@]}"
}

I get below error when I pass gcp ci list stg as an argument , however it works fine with gcp c i list stg

ERROR: (gcloud) Invalid choice: 'compute instances'.
Maybe you meant:
  gcloud compute instances

could it be because compute instances is being passed as a single argument to gcloud rather than two ?

1 Answer 1

0

${translation[ci]} is a single word (which happens to have a space character in it), but the gcloud command needs compute and instances as separate arguments. The best way to store a list of words is as an array, but you can't put an array into another array (whether they're plain arrays or associative arrays). So keep storing ${translation[ci]} as a single string, but when you expand ${translation[$arg]}, split it into separate words on whitespace. (You can pick any separator character as long as it doesn't appear inside any of the arguments you want to end with, but whitespace is intuitive and is the easiest to work with.)

Change

args+=("${translation[$arg]}")

to

args+=($=translation[$arg])

The = sign before the parameter name in parameter expansion instructs zsh to split the string into separate words at whitespace. (More precisely, the word separators are given by the value of IFS, but unless you've changed IFS in your script, don't worry about this.)

1
  • Good Explanation @Gilles , Thanks
    – Learner
    Commented Dec 22, 2020 at 21:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .