What is the difference in between adding "read" or "read -rn1" to the end of a bash script?

I've written a simple bash script for running rsync in between two directories, and I wanted it to keep the terminal window open after it runs, so I can check if everything went fine.

So, I found two different solutions in this topic, that is adding either the command read or read -rn1 to the end of the script, and I'm wondering what would be the difference in between them, and if I should prefer using one over the other, since both seems to do the same.

2 Answers

read waits for a line ending with a newline, then ends. So only the enter key allows you to complete the command and, therefore in your case, to close the terminal window.

read -n1 waits for a single character, then ends. So a single press on any key terminates the command and, therefore in your case, closes the terminal window.

However, I don't see the usefulness of the -r option in your case

For more info on the bash builtin command read:

  • man bash (see read in the SHELL BUILTIN COMMANDS section)
  • help -m read
1

You can run read --help to see what -rn1 does.

Running read -rn1 is the same as read -r -n1

-r do not allow backslashes to escape any characters

-n nchars return after reading NCHARS characters rather than waiting for a newline, but honor a delimiter if fewer than NCHARS characters are read before the delimiter

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like