Skip to content

zsh tricks for code golf

bash is arguably the de facto Unix shell nowadays, which makes it a popular language for code golf. But the expressive power zsh is often overlooked, making it easy to score loads of points.

Some/many of these tricks apply to bash as well, but in many cases zsh

RTFM!

man zsh provides an overview of the manual pages for zsh, which are the comprehensive reference which will be very useful to you. zshall(1) includes all of the pages for easy searching (type /pattern, assuming your pager is GNU less). zshexpn(1) is particularly useful (various expansion syntax: variable, command, etc.)

Functions

function longest {
    echo hi
}

shorter () {
    echo hi
}

tiny()echo hi

# multiple names for the same function:
f1 f2()echo hi

f1  # => hi
f2  # => hi

Loops

For-each

for i in a b c; do; echo $i; done
for i in a b c; { echo $i }
for i (a b c)echo $i

C-style

i = 0
while $((i < 10)); do echo $i; $((i++)); done
for ((i = 0; i < 10; i++)) { echo $i }
for ((i=0;i<10;i++))echo $i

Infinite

while true; do echo hi; done
while :; do echo hi; done
for ((;;))echo hi

No-op

# ignores all input and arguments
:

Maths

a=$((a+1))
: $((a+=1))
$((a++))
$((++a))
# executes, but then tries to find a command named (the new value), so errors
$((a+=1))

$((a+b))
# deprecated, but still works, and shorter
$[a+b]

Command Substitution

$(echo hi)
# can't be nested, but shorter
`echo hi`

Conditionals

[[ a = b ]]
# more limited syntax (see `man test`)
[ a = b ]
# useful for restricted-source
test a = b

# only works if you know the "if-true" command won't fail
if [ a = b ]; then echo hi; else echo hi; fi
[ a = b ]&&echo hi||echo no

# `a` is non-empty
[ -n a ]
[ a ]