2

In bash:

foo_a=1
foo_b=2
declare -p ${!foo_*}

Outputs:

declare -- foo_a="1"
declare -- foo_b="2"

How do I do this in zsh?

Why won't pasting the above into zsh fail to even set the variables? It appears as if pasting a piece of code has no effect whatsoever unless all of the pasted code succeds? What's up with that?

2 Answers 2

2
  1. How to print all parameters starting with foo:

    declare -p ${(Mk)parameters:#foo*}
    

    All variables are stored in the parameters associative array, so it is enough to print all its keys (k) and search for pattern foo*. The flag (M) is present to remove non-matching elements.

    Output:

    typeset foo_a=1
    typeset foo_b=2
    

    (notice that declare is the same as typeset).


  1. Pasting doesn't work as expected because of recently introduced feature called bracketed_paste:

    zle_bracketed_paste

    Many terminal emulators have a feature that allows applications to identify when text is pasted into the terminal rather than being typed normally. For ZLE, this means that special characters such as tabs and newlines can be inserted instead of invoking editor commands. Furthermore, pasted text forms a single undo event and if the region is active, pasted text will replace the region.

    This two-element array contains the terminal escape sequences for enabling and disabling the feature. These escape sequences are used to enable bracketed paste when ZLE is active and disable it at other times. Unsetting the parameter has the effect of ensuring that bracketed paste remains disabled.

    Just unset if you don't like it:

    unset zle_bracketed_paste
    
1

@jimmij gave a great answer, and that works in the general case for printing the matches to the pattern for each key in an associative array.

In the case of zsh environment variables, however, there's a built-in solution I found using the typeset command when I was reading man zshbuiltins.

You can just use typeset's -m option, and supply in quotes the pattern of parameter names you are trying to match.

Printing Environment Variables Matching a Pattern

  • Just the variable name:

    typeset +m 'foo*'
    
    foo
    foo_fighters
    food
    
  • Variable name and assigned value:

    typeset -m 'foo*'
    
    foo=bar
    foo_fighters=awesome
    food=(my life)
    
  • Typeset flags, variable name, and assigned value

    typeset -p -m 'foo*'
    
    typeset foo=bar
    typeset foo_fighters=awesome
    typeset -a food=( my life )
    

You must log in to answer this question.

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