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


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.)


function longest {
    echo hi

shorter () {
    echo hi

tiny()echo hi

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

f1  # => hi
f2  # => hi



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


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


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


# ignores all input and arguments


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

# deprecated, but still works, and shorter

Command Substitution

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


[[ 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 ]