1

I'm using echo $(cal) and echo "$(cal)"in Linux and it gives me different results as in the picture. The double quotes should not interfere with $ in this case, so what gives the echo "$(cal)" that horizontal style comparing to echo $(cal).

This is the result:

Screenshot of output

echo "$(cal)"

Su Mo Tu We Th Fr Sa  
                   1  
 2  3  4  5  6  7  8  
 9 10 11 12 13 14 15  
16 17 18 19 20 21 22  
23 24 25 26 27 28 29  
30

echo $(cal)

June 2019 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Greenonline
  • 2,235
  • 11
  • 24
  • 30
ItsJay
  • 13
  • 3

1 Answers1

1

There are two key differences:

  1. The shell performs word splitting on the unquoted $(cal). This means, assuming a default value for IFS, that all strings of white space (including newlines) are replaced with a single blank. This is the output from the unquoted command is on a single line.

    Here is a simpler example:

    $ s='line     1
    > line  2'
    $ echo "$s"
    line     1
    line  2
    $ echo $s
    line 1 line 2
    

    As you can see, in the second echo, the one without double quotes, all sequences of white space have been replaced by single blanks. This is just what you saw when using echo without double-quotes with echo $(cal).

  2. The shell performs pathname expansion on the result of the word splitting. This doesn't happen to make any difference in your example but, if your output included ? or * or other glob-active characters, it could lead to some surprises.

    Here is a simple example of pathname expansion. Let's start with a directory with three files:

    $ ls
    file1  file2  file3
    

    Now, let's define a string: $ s='file?'

    Now, see that echo with double-quotes returns our string but, without double-quotes, the string is expanded into file names:

    $ echo "$s"
    file?
    $ echo $s
    file1 file2 file3
    
John1024
  • 16,593
  • 5
  • 50
  • 45