When I write:
echo 2*3>5 is a valid inequality
In my bash terminal, a new file named 5
is created in my directory which contains:
2*3 is a valid inequality
I want to know what exactly is going on here and why am I getting this output? I believe it's obvious that I'm new to Linux! Thanks
The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.
There are a couple of different ways we can print a newline character. The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.
To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.
Echo is a Unix/Linux command tool used for displaying lines of text or string which are passed as arguments on the command line. This is one of the basic command in linux and most commonly used in shell scripts.
In bash, redirections can occur anywhere in the line (but you shouldn't do it! --- see the bash-hackers tutorial). Bash takes the >5
as a redirection, creates output file 5
, and then processes the rest of the arguments. Therefore, echo 2*3 is a valid inequality
happens, which gives you the output you see in the output file 5
.
What you probably want is
echo "2*3>5 is a valid inequality"
or
echo '2*3>5 is a valid inequality'
(with single-quotes), either of which will give you the message you specify as a printout on the command line. The difference is that, within ""
, variables (such as $foo
) will be filled in, but not within ''
.
Edit: The bash man
page says that the
redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right.
bash
does the output redirection first i.e. >5
is done first and a file named 5
is created (or truncated if it already exists). The resultant file descriptor remains open for the runtime of the echo
command.
Then the remaining portion, 2*3 is a valid inequality
, runs as the argument to echo
and standard output is saved in the (already-open) file 5
eventually.
To get the whole string as the output, use single or double quotes:
echo '2*3>5 is a valid inequality'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With