Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does bash script add single quotes to string with asterisk?

Tags:

bash

I'm trying to make a little script as a wrapper around this command:

$ egrep target /usr/lusers/me/test/*test.txt 
/usr/lusers/me/test/1test.txt:target

That directory has files called 1test.txt and 2test.txt, one of which contains some text I want to find.
Here is my whole script, called mygrep.sh:

set -v
set -x
egrep "$1" '/usr/lusers/me/test/*test.txt'

Here's the output:

$ ./mygrep.sh target
set -x
egrep "$1" '/usr/lusers/me/test/*test.txt'
++ egrep targ '/usr/lusers/me/test/*test.txt'
egrep: /usr/lusers/me/test/*test.txt: No such file or directory

Note the 's around the file path in the set -x output, and that the command fails.

Now compare this variation of the script:

set -v
set -x
egrep "$1" '/usr/lusers/me/test/1test.txt'

Note that the only difference is the asterisk vs the literal file name.
Output:

$ ./mygrep.sh target
set -x
egrep "$1" '/usr/lusers/me/test/1test.txt'
++ egrep target /usr/lusers/me/test/1test.txt
target

No single quotes after expansion, and the command works.

So why are those single quotes added when there's an asterisk, and why is the command failing in that case?

like image 298
Jacktose Avatar asked Dec 18 '25 01:12

Jacktose


2 Answers

The output resulting from set -x is for debugging purposes. No quotes are added to the argument; they are just for display purposes.

The correct command is egrep "$1" /usr/lusers/me/test/*.test.txt, because the shell must expand the pattern (if possible) before passing the results to egrep. You don't have an actual file named *.test.txt.

like image 155
chepner Avatar answered Dec 20 '25 16:12

chepner


The globbing character must be outside (single or double) quotes, as quotes disable globbing.

Use this instead :

egrep "$1" '/usr/lusers/me/test/'*'test.txt'

Or this :

egrep "$1" "/usr/lusers/me/test/"*"test.txt"

Or, since there is nothing inside this specific pattern that would cause word splitting to occur (but that would not be a generally safe way to do it if the path is not known safe in advance) :

egrep "$1" /usr/lusers/me/test/*test.txt
like image 33
Fred Avatar answered Dec 20 '25 16:12

Fred



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!