Shell scripting: cat vs echo for output

I wrote a small script in bash that parses either the files provided or stdin if the file is not provided to get some result. What is the best way to redirect processed 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?

+7
source share
3 answers

Use the printf command:

 printf '%s\n' "$var" 

echo is suitable for simple cases, but it can behave strangely for certain arguments. For example, echo has the -n option, which tells it not to print a new line. If $var turns out to be -n , then

 echo "$var" 

doesn't print anything. And there are several different versions of echo (either built into different shells, or like /bin/echo ) with subtly different behavior.

+9
source

echo is a great way to do this. You will need to slip through a few hoops if you want cat to work.

+3
source

echo. You have parsed data in a variable, so just echo "$var" should be fine. cat is used to print the contents of files, which you do not want here.

+3
source

All Articles