Zsh

🡸
last updated:

Process Substitution

Anonymous Functions

Declared:

() {
    ...
} arg1 arg2...

Runs immediately after declaration closes (}), with args if present.

‘Main use … is to provide scope for local variables’.

Args passed become argv list inside the function ($1, $2, etc.).

Useful pattern to edit a temp file version of a file, and if temp and orig differ, then replace orig with temp:

f=$1
() {
    ${EDITOR} -- $1
    if (( $(wc -c <$1) )) \
        && diff -q $f $1 &>/dev/null
    then
            mv -f $1 $f
    fi
} =(<$f)

simple redirection

<& - command             # disable stdin for command
&>flie                   # redirect both stdout and stderr

<<<"string with $var"    # one-line input with parameter expansion
<<<$(command)            # substitute command

<<<$(...) and <<(...) are similar
i don't know the *actual* difference...

other shorthand

(( $# ))                # same as '[[ $# -gt 0 ]]'
[[ $var ]]              # same as '[[ -n $var ]]'

if read -sq '?(y/N): '  # single-key yes-no

[[ $n = <-> ]]          # check if $n is a digit
(( $n ))                # check if $n is not zero (prints error if not digit)

---
# pop $n element from $array
array[$n]=
array=(${(@)array})

[[ ${e:*array} ]]       # check if $e is a member of $array
[[ ${e:|array} ]]       # check if $e is not in $array

---
# turn on glob_subst to make parameter expansion part of glob evaluation
# (really only useful for scripts or functions)

exts=('jpe#g' gif png)  # quote extended_glob characters to prevent eval
*.(${(j.|.)exts})       # turns into *.(jpe#g|gif|png)

---
# extended_glob
dir/*(#qN)              # null-glob (returns nothing if no match)

[[ dir/*(#qN) ]]        # check if dir empty (glob_dots enabled)
[[ dir/{.,}*(#qN) ]]    # same, if glob_dots disabled
[[ dir(#qN)(/^F) ]]     # also works