Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does bash "echo [t]" result in "t" not "[t]"

Tags:

bash

This happens for the character t, and the value root. Quite perplexing

$ echo [s] [s] $ echo [t] t $ echo [ t ] [ t ] $ echo [root] t 
like image 619
user3546411 Avatar asked Apr 17 '14 18:04

user3546411


People also ask

How does echo work bash?

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.

What does echo stand for in bash?

Echoes (prints) the exit value for the previous command. If it failed it will be different than zero ( 0 ).

How do I echo a line in bash?

Printing Newline in Bash 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. However, it's also possible to denote newlines using the “$” sign.


1 Answers

[] denotes a character class, and you have a file named t in your current directory.

The following should explain it further:

$ ls $ echo [t] [t] $ touch t $ echo [t] t $ echo [root] t $ touch r $ echo [root] r t 

If you want to echo something within [], escape the [:

echo \[$var] 

Observe the difference now:

$ echo \[root] [root] 

or, as Glenn Jackman points out, quote it:

$ echo '[root]' [root] $ echo "[root]" [root] 

Shell Command Language tells that the following characters are special to the shell depending upon the context:

*   ?   [   #   ~   =   % 

Moreover, following characters must be quoted if they are to represent themselves:

|  &  ;  <  >  (  )  $  `  \  "  '  <space>  <tab>  <newline> 

You could also use printf to determine which characters in a given input need to be escaped if you are not quoting the arguments. For your example, i.e. [s]:

$ printf "%q" "[s]" \[s\] 

Another example:

$ printf "%q" "[0-9]|[a-z]|.*?$|1<2>3|(foo)" \[0-9\]\|\[a-z\]\|.\*\?\$\|1\<2\>3\|\(foo\) 
like image 167
devnull Avatar answered Sep 22 '22 02:09

devnull