I've written a small script in bash that parses either the provided files or stdin if no file is given to produce some output. What is the best way to redirect the parsed output to stdout (at the end of the script the result is stored in a variable). Should I use cat
or echo
, or is there another preferred method?
Use the printf
command:
printf '%s\n' "$var"
echo
is ok for simple cases, but it can behave oddly for certain arguments. For example, echo
has a -n
option that tells it not to print a newline. If $var
happens to be -n
, then
echo "$var"
won't print anything. And there are a number of different versions of echo
(either built into various shells or as /bin/echo
) with subtly different behaviors.
echo. You have your parsed data in a variable, so just echo "$var"
should be fine. cat is used to print the contents of files, which isn't what you want here.
echo
is a fine way to do it. You will have to jump through a few hoops if you want cat
to work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.