You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Michael Diamond edited this page Dec 16, 2021
·
11 revisions
read without -r will mangle backslashes.
Problematic code:
echo"Enter name:"read name
Correct code:
echo"Enter name:"read -r name
or
echo"Enter name:"
IFS= read -r name
Rationale:
By default, read will interpret backslashes before spaces and line feeds (i.e. you can use backslashes in your string as an escape character). This is rarely expected or desired.
Normally you just want to read data including backslashes which are part of the input string and have no special escape meaning, which is what read -r does. You should always use -r unless you have a good reason not to:
-r
If this option is given, backslash does not act as an escape character.
Trimming whitespace
Even with read -r, leading and trailing whitespace will be stripped from the input. Although this may sometimes be desirable or harmless it is often surprising and difficult to catch. Clearing the IFS disables this behavior, so IFS= read -r is generally safest.