質問

I'm writing a bash script that extensively uses wget. To define all common parameters in one place I store them on variables. Here's a piece of code:

useragent='--user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0"'
cookies_file="/tmp/wget-cookies.txt"
save_cookies_cmd="--save-cookies $cookies_file --keep-session-cookies"
load_cookies_cmd="--load-cookies $cookies_file --keep-session-cookies"

function mywget {
    log "#!!!!!!!!!# WGET #!!!!!!!!!# wget $quiet $useragent $load_cookies_cmd $@"  
    wget $useragent $load_cookies_cmd "$@"
}

Saddly isn't working. Somehow I'm missing the right way to store parameters on variables $useragent, $save_cookies_cmd, $load_cookies_cmd and caling wget passing these vars as parameters.

I want the result commandline as this:

wget --user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0" --load-cookies /tmp/wget-cookies.txt --keep-session-cookies http://mysite.local/myfile.php
役に立ちましたか?

解決

Drop the inner quotes when setting $useragent, but retain the double quotes when you use it:

useragent='--user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0'
...
wget "$useragent" $load_cookies_cmd "$@"

To understand why this works, notice that wget --user-agent="string with spaces" is entirely equivalent to wget "--user-agent=string with spaces". Wget receives (and must requires) the --user-agent=... option as a single argument, regardless of the positioning of the quotes.

The quotes serve to prevent the shell from splitting the string, which is why wget "$useragent" is necessary. On the other hand, the definition of user-agent needs quotes for the assignment to work, but doesn't need a second level of quotes, because those would be seen by Wget and become part of the user-agent header sent over the wire, which you don't want.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top