0

I have the following statement in a bash script:

ssh $host "cd /directory; for i in *$date.gz; do echo $i; done; exit"

I expect it to print the name of each file in the directory that ends with the date, and is a zip file. By ssh-ing to the host on the command line, and searching the directory, I find that there should be 5 such files. However, this script returns 5 blank lines. I checked if the $date variable was properly defined inside the quotes (it was). When I replaced $i with 'adf', the script printed

adf
adf
adf
adf
adf

So it is correctly filtering out those 5 files, but it is just not printing their names, and is replacing the $i in the statement with nothing (so that that line is just echo). Why is it doing this, and how can I make it print the filenames? The same thing happens when I run this line on the command line.

1 Answer 1

1

By double-quoting your command, the variable expansion occurs before the ssh call.

So when you call this command line:

ssh $host "cd /directory; for i in *$date.gz; do echo $i; done; exit"

It calls the ssh command with two arguments: $host and "cd /directory; for i in *$date.gz; do echo $i; done; exit"

The second argument picks the content of the date variable and the i variable when the string is built. But at this time, you do NOT have the correct value for i yet.

I think that escaping $i into \$i should solve your issue:

ssh $host "cd /directory; for i in *$date.gz; do echo \$i; done; exit"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.