Skip to content

Instantly share code, notes, and snippets.

@moisoto
Last active November 26, 2019 16:25
Show Gist options
  • Save moisoto/532f07cfeb7911398ea4358221599340 to your computer and use it in GitHub Desktop.
Save moisoto/532f07cfeb7911398ea4358221599340 to your computer and use it in GitHub Desktop.
MacOS: ZSH Tidbits

Working with ZSH Options

When using ZSH as your default shell there is a chance you’ll set specific options on your .zshrc script to make work easier.

You can read about ZSH options and what they do here for more information on what you can do with zsh options.

Problem is, when doing ZSH scripts you can’t depend on the user having specific options. So you must be careful that you are not assuming the script works on any environment since your script may be depending on your specific options. Also the user may set an option that breaks your script.

To avoid this, you should set there following code at the start of all your zsh scripts:

# Set Default ZSH Options
emulate -LR zsh

Also you may need to set specific options on your scripts to make them work in certain scenarios.

Let’s see this with the following example. A script that list all .txt files located on the same directory where the script is running:

#!/bin/zsh

# Set Default ZSH Options
emulate -LR zsh

for f in *.txt ; do
    # Test File Exists
    if [ ! -e "$f" ] ; then
        echo "There are no text files"
        exit
    fi
    echo "Found File: $f"
done

When running this script on a folder with no .txt files, it will abort with the following error:

❯ ./test_nomatch.zsh
./test_nomatch.zsh:8: no matches found: *.txt

To avoid this, you must use NO_NOMATCH option in the following way:

#!/bin/zsh

# Set Default ZSH Options
emulate -LR zsh

#Avoid "no matches found" error
setopt NO_NOMATCH
for f in *.txt ; do
    # Test File Exists
    if [ ! -e "$f" ] ; then
        echo "There are no text files"
        exit
    fi
    echo "Found File: $f"
done
setopt NOMATCH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment