1

I'm currently re-learning shell scripting. I'm making a script that checks r/EarthPorn and randomly pick a post, go to that post and download the image. Then set it as a background.

For some reason, i'm getting this:

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/

This is what I have so far:

#!/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

So the initial wget works fine, and links contains the proper links. But I don't know why the 2nd wget is saying that $LINK is not found. When I echo it, it returns a good link that I works fine. When I run wget outside of the script with the same link, it works perfectly. Could I get some pointers?

  • $(LINK) is a command substitution - did you mean to use a simple variable expansion $LINK or ${LINK}? – steeldriver Sep 10 '18 at 0:12
  • My goodness, please excuse me as I'm a noob. Thank you for answering so quickly! – lanmvil Sep 10 '18 at 0:14
  • You can save some lines with LINK=$(shuf -n1 links) for getting a random line. – Ipor Sircer Sep 10 '18 at 0:26
2

The sequence $(...) causes the stuff inside the brackets to run, and then return the output to the caller.

So, for example,

mydata=$(grep foobar myfile)

will set $mydata to be the results of the grep command.

In your case you just want $LINK to expand the variable.

What you might have been thinking of is ${LINK} which is a way of enforcing the scope of the interpretation of the variable name.

For example, echo $a_b would look for the variable a_b but echo ${a}_b would look for the variable a then add add _b to the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.