Linux

wgrep 在腳本中找不到變數

  • September 10, 2018

我目前正在重新學習 shell 腳本。我正在製作一個腳本來檢查 r/EarthPorn 並隨機選擇一個文章,轉到該文章並下載圖像。然後將其設置為背景。

出於某種原因,我得到了這個:

URL transformed to HTTPS due to an HSTS policy
--2018-09-09 19:56:10--  https://www.reddit.com/r/EarthPorn
Resolving www.reddit.com (www.reddit.com)... 151.101.125.140
Connecting to www.reddit.com (www.reddit.com)|151.101.125.140|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 485053 (474K) [text/html]
Saving to: ‘STDOUT’

-                         100%[==================================>] 473.68K  1.69MB/s    in 0.3s    

2018-09-09 19:56:12 (1.69 MB/s) - written to stdout [485053/485053]

./wallpaper.sh: 13: ./wallpaper.sh: LINK: not found
http://: Invalid host name.
www.reddit.com/r/EarthPorn/comments/9ef7bi/picture_i_took_hiking_mount_sulphur_banff/

這是我到目前為止所擁有的:

#!/bin/sh
wget -O - www.reddit.com/r/EarthPorn > file
#1 Get all the post links from the subreddit r/EarthPorn
grep -Po '(?<=href="https://www.reddit.com/r/EarthPorn/comments/)[^"]*' file > links
#2 Fix the links
sed -i -e 's~^~www.reddit.com/r/EarthPorn/comments/~' links
#3 Count the # of posts there are
POST_NUMBER="$(wc -l < links)"
#4 Choose a random number to pick which wallpaper we're going to use
NUMBER=$(shuf -i 1-$POST_NUMBER -n 1)
LINK=$(sed -n ${NUMBER}p < links)
wget -O - "$(LINK)" > picture
echo $LINK
#5 Get the picture link and save it

所以最初的 wget 工作正常,並且連結包含正確的連結。但我不知道為什麼第二個 wget 說 $LINK 沒有找到。當我回顯它時,它會返回一個我可以正常工作的良好連結。當我使用相同的連結在腳本之外執行 wget 時,它可以完美執行。我可以得到一些指示嗎?

該序列$(...)使括號內的內容執行,然後將輸出返回給呼叫者。

所以,例如,

mydata=$(grep foobar myfile)

將設置$mydatagrep命令的結果。

在您的情況下,您只想$LINK擴展變數。

您可能一直在想的是${LINK},這是一種強制變數名解釋範圍的方式。

例如, echo $a_b會查找變數a_b,但echo ${a}_b會查找變數a然後將 add 添加_b到結果中。

引用自:https://unix.stackexchange.com/questions/467947