howto 

Send to Kindle
home » snippets » zsh » howto



Snippets

How to detect of this script is running under zsh.

# ZSH_VERSION is set by zsh but not exported.  So checking for it
# is a good way to see if running under zsh.
if [[ -z $ZSH_VERSION ]]; then
  echo Not running under zsh.
  exit 4
fi

How to detect of this script was "source"d by zsh.

Ref: Parameters Set By The Shell

# zsh_eval_context is an array of contexts - the last element is the
# current context.  zsh_eval_context = "file" when sourced by a file
# and "filecode" when sourced as ".zwc"
if [[ -z $ZSH_EVAL_CONTEXT || $zsh_eval_context[-1] != file* ]]; then
  echo This file must be sourced from a zsh script.
  exit 4
fi

Set array to a set of lines

# To test that $A doesn't get expanded
A=VAR_A

# -r/raw mode: to ignore the backslashes, etc.
# -d '': No delimiter.  Read until the end of the stream.
# -A lines:  Read into the array variable "lines".
IFS=$'\n' read -r -d '' -A lines <<"EOF"
a b c
$A 'bc'
$'\n'
'"\
EOF

print_args $lines

When run,

Received 4 args
1: 'a b c'
2: "$A 'bc'"
3: "$'\\n'"
4: '\'"\\'