A question on Bash echo command

Hi all,
When I run the following script, the resulting output is:

*There are 3 entries in the directory /home/inor/MyLibraries

Only the first asterisk is printed.

#!/bin/bash

sampledir=/home/inor/MyLibraries

myvar=$( ls /home/inor/MyLibraries | wc -l )

echo *There are $myvar entries in the directory /home/inor/MyLibraries*

However, if I include the echo statement in double quotes both asterisks are printed.

Can anyone please explain whats going on here?

1 Like

Hi,

Actually it is a common practice (a good practice) to put everything what you echo in double quotes.

If you echo something without double quotes it takes each word separated with a white space as a new argument and output it.

In linux the asterisk (*) character is a wildcard and it matches one or more occurrences of any character , including no character at all.

Therefore, when the turn comes to output the /home/inor/MyLibraries* the asterisk is replaced by any matching character to match the MyLibraries..... folders. So if you have there MyLibraries folder and two more like MyLibraries_copy and MyLibraries_Second_copy you will then actually see the output of all such directories.

For example, you can perform the following four commands in the terminal:

touch text1
touch text2
touch text3
touch text

and then run echo text* and you will something like this:

$ echo text*
text text1 text2 text3

if you execute echo * it will match all the directories and files in the folder.

1 Like

Oh, of course! Ha now I feel stupid. I just thought I’d put the asterix to make the text “stand out” a little. Thanks for that.