我目前正在重新学习 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 工作正常,并且 links 包含正确的链接。但我不知道为什么第二个 wget 说找不到 $LINK。当我回显它时,它会返回一个很好的链接,我工作得很好。当我使用相同的链接在脚本外部运行 wget 时,它工作得很好。我可以得到一些指点吗?
答案1
该序列$(...)
导致括号内的内容运行,然后将输出返回给调用者。
所以,举例来说,
mydata=$(grep foobar myfile)
将设置$mydata
为命令的结果grep
。
在你的情况下,你只想$LINK
扩展变量。
您可能想到的是${LINK}
这是一种强制变量名解释范围的方法。
例如, echo $a_b
将查找变量a_b
,但echo ${a}_b
会查找变量a
然后将 add 添加_b
到结果中。