Skip to content

Instantly share code, notes, and snippets.

@moisoto
Last active November 26, 2019 02:46
Show Gist options
  • Save moisoto/8bc022c289714a65a331ca9a2fbf1734 to your computer and use it in GitHub Desktop.
Save moisoto/8bc022c289714a65a331ca9a2fbf1734 to your computer and use it in GitHub Desktop.
macOS: ZSH Tidbits

ZSH Tidbits: Working with the read command

The read command can be a headache when you are porting your scripts from a shell to another.

Let's see the way it works with bash (the default shell for macOS before Catalina):

read -p "Do you wish to continue? (Y/n)"
[[ $REPLY == "y" ]] && echo "You must use Capital Y if you wish to continue"
[[ $REPLY != "Y" ]] && exit

This sintax will also work in Bourne Shell (sh), but on Korn Shell (ksh) and Z Shell (zsh) it takes another form: :wq

read REPLY"?Do you wish to continue? (Y/n)"
[[ $REPLY == "y" ]] && echo "You must use Capital Y if you wish to continue"
[[ $REPLY != "Y" ]] && exit

The variable name could be anything, but we use REPLY for simplicity. Also on ZSH if you omit the variable it will use the REPLY variable.

So, there we have two versions of the read command to display a message and read a keystroke from the user. It's not the end of the world, but I try to make scripts the most portable they can be.

So, how do we accomplish the same in a way that works (at least) on sh, bash, ksh, and zsh? The most simple sintax for read could be of help.

echo -n "Do you wish to continue? (Y/n)"
read REPLY
[[ $REPLY == "y" ]] && echo "You must use Capital Y if you wish to continue"
[[ $REPLY != "Y" ]] && exit

However, there's a little problem with the echo command. We use the -n switch to avoid the '\n' character at the end of the displayed message, so the cursor appears in the same line of the echoed text. However, on Bourne Shell (sh) there's no -n swith for the echo.

In the BSD man page for the echo command, you can see the use of the -n switch is discouraged and instead they propose the use of printf instead. Let's do one last change to our code and be done with this:

printf "Do you wish to continue? (Y/n)"
read REPLY
[[ $REPLY == "y" ]] && echo "You must use Capital Y if you wish to continue"
[[ $REPLY != "Y" ]] && exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment