Using wildcards and quotation marks in ssh

1.1k views Asked by At

I have a file that I want to grep out lines with strings like "Nov 30" or "Nov 30" (basically I don't want to specify the number of spaces in the middle.

In the terminal this would be fine, I'd just do:

grep 'Nov * 30' file

However, it'd be nice to keep it general for my purposes, so in fact I'd like to do something like:

grep "$(date +%b) * $(date +%d)" file

That works fine BUT I actually want to do this through ssh so it'd be like

ssh -t host "grep "$(date +%b) * $(date +%d)" file"

At this point I run into problems. Instead of grepping only for Nov 30 type date strings, it returns all sorts of different November dates. I feel like the problem has something to do with double quotation usage (perhaps the first set of double quotes for the -t argument is affecting the second lot, but I don't see how to get around that) , and I see from this answer that "bash will evaluate and substitute variables inside double-quotes on the local machine but will do it on the target machine inside single quotes". So I tried replacing the above with

ssh -t host "grep '$(date +%b) * $(date +%d)' file"

But now the grep returns no results at all! I assume this is because I'm grepping for literal '$(date +%b)...' and not the substituted 'Nov..', but then I don't understand why the first attempt with double quotes didn't work.

Welcome any help

3

There are 3 answers

0
Lynch On

Escape your quotes:

ssh -t host "grep \"$(date +%b) * $(date +%d)\" file"
0
janos On

In this version the date command will be executed locally:

ssh -t host "grep '$(date +%b) * $(date +%d)' file"

In this version the date command will be executed on the remote host:

ssh -t host 'grep "$(date +%b) * $(date +%d)" file'

This can make a difference when your local PC and server are in different time zone. Right now for example, it's Dec 1 in France, but Nov 30 on my server in the US.

In the 1st version the $() within the double quotes are evaluated before sending to the server. So the command sent to the server is grep 'Dec * 1' file in my timezone.

In the 2nd version the $() within single quotes are NOT evaluated before sending to the server. So the command sent to the server is grep "$(date +%b) * $(date +%d)" file, and so the server will evaluate the $() within double quotes.

0
pobrelkey On

Alternately, single-quote the command line you wish to execute on the remote machine. (In this case the date commands will execute on the remote end.)

ssh -t host 'grep "$(date +%b) * $(date +%d)" file'