Skip to content

Instantly share code, notes, and snippets.

@bitmvr
Last active January 6, 2024 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitmvr/da7c7a69e8d5bdce9485c020bca6184c to your computer and use it in GitHub Desktop.
Save bitmvr/da7c7a69e8d5bdce9485c020bca6184c to your computer and use it in GitHub Desktop.
hackn - A lightweight hacker news CLI tool.
#!/usr/bin/env bash
NUM_OF_STORIES="$1"
getTopStoryIds(){
curl -sL "https://hacker-news.firebaseio.com/v0/topstories.json" | tr -d '[]' | tr ',' '\n'
}
getStoryData(){
storyID="$1"
curl -sL "https://hacker-news.firebaseio.com/v0/item/${storyID}.json?print=pretty"
}
getTitle(){
response="$1"
title="$(echo "$response" | grep -E '^\s*"title"')"
title="${title#*: }"
title="${title#*\"}"
title="${title%\"*}"
echo "$title"
}
getURL(){
response="$1"
url="$(echo "$response" | grep -E '^\s*"url"')"
url="${url#*: }"
url="${url#*\"}"
url="${url%\"*}"
echo "$url"
}
main(){
readonly TOP_STORY_IDS="$(getTopStoryIds)"
num_of_stories=${NUM_OF_STORIES:=10}
story_rank=1
for story_id in $TOP_STORY_IDS; do
story_data="$(getStoryData "$story_id")"
if [ "$story_rank" -le $num_of_stories ]; then
story_title="$(getTitle "$story_data")"
story_URL="$(getURL "$story_data")"
echo "[${story_rank}] ${story_title}"
echo " - ${story_URL}"
echo ""
else
exit 0
fi
story_rank=$((story_rank+1))
done
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment