Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell scripting: cat vs echo for output

Tags:

bash

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?

like image 820
Explosion Pills Avatar asked Nov 16 '11 01:11

Explosion Pills


2 Answers

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.

like image 195
Keith Thompson Avatar answered Nov 24 '22 01:11

Keith Thompson


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.

like image 31
Jarek Avatar answered Nov 24 '22 01:11

Jarek