jeremyforan
jeremyforan

Reputation: 1437

bash scripting yesterdays zip file

#!/bin/bash

yesterday= date --date="1 day ago" +%Y%m%d | tr -d '\n'
remote_file="76.99.20.129\$yesterday.zip"

echo $remote_file

output:

2012010476.99.20.129$yesterday.zip

What is going on here?

I want to pass this variable to a wget call and automatically download a file

Upvotes: 1

Views: 675

Answers (2)

paxdiablo
paxdiablo

Reputation: 881093

Two problems here. The first is that you're actually not capturing the output of the date command in the variable:

pax> yesterday= date --date="1 day ago" +%Y%m%d | tr -d '\n'
20120105pax@pax-desktop:~$ echo $yesterday
<<no output>>

What that command of yours is doing is setting yesterday to an empty string for the duration of running the date command, a nifty bash feature I call the one-shot environment setting but which bash almost certainly calls something else. It's no different to:

xyzzy=plugh dosomething

in which the dosomething command has an entry for xyzzy in its environment but, on return, the shell that started it doesn't. Note that this is different from:

export xyzzy=plugh
dosomething
# Here xyzzy is still set.

The second is that you're escaping the $, meaning the variable won't be touched.

Try:

pax> yesterday=$(date --date="1 day ago" +%Y%m%d)
pax> remote_file="76.99.20.129_${yesterday}.zip"
pax> echo ${remote_file}
76.99.20.129_20120105.zip

I put the underscore in just so you could see the delineation clearly. Remove it to get the behaviour (I think) you originally intended.

If the string you're actually after should have the backslash in it, you'll need to escape that so it doesn't affect the $:

pax> yesterday=$(date --date="1 day ago" +%Y%m%d)
pax> remote_file="76.99.20.129\\${yesterday}.zip"
pax> echo ${remote_file}
76.99.20.129\20120105.zip

Note the double \ above to achieve the escaping.

You'll also note that I've surrounded environment variable names with {}. This is good practice to avoid problems where you want to add (for example) the letter d to the contents of the environment variable abc.

The command echo $abcd will give you the contents of the abcd environment variable whereas what you need is echo ${abc}d. I always prefer this explicit notation.

In addition, thanks to holygeek, the tr -d '\n' is not really necessary in this case, so I've removed it as well.

Upvotes: 3

J-16 SDiZ
J-16 SDiZ

Reputation: 26910

use ${} to escape:

remote_file="76.99.20.129\\${yesterday}.zip"

Upvotes: 1

Related Questions