Skip to main content

Creating a Bash Script for Fetching News in the Terminal

This tutorial will walk you through creating a small Bash script that uses curl to fetch news about a specified topic and print it in the terminal. We'll use getnews.tech as the news source. The script will also include a help flag for users to understand how to use it.

Prerequisites

Make sure you have curl installed on your Linux system. You can verify this by typing curl --version in your terminal. If it's not installed, use your distribution's package manager to install it, such as sudo apt install curl for Debian-based systems.

Step 1: Create the Bash Script

  1. Open a Text Editor: Open your preferred text editor and create a new file.

  2. Start with the Shebang: At the top of the file, add the shebang line for Bash:

    #!/bin/bash
  3. Write the Basic Script Structure:

    if [[ "$1" == "-h" || "$1" == "--help" ]]; then
    echo "Usage: $0 [search-term]"
    echo "Example: $0 world+cup"
    echo "Fetches and displays news about the specified topic."
    exit 0
    fi

    SEARCH_TERM=$1
    curl "getnews.tech/${SEARCH_TERM}"
  4. Save the Script: Save this file as fetch_news.sh.

Step 2: Explaining the Script

  • if [[ "$1" == "-h" || "$1" == "--help" ]]; then ... fi: This block checks if the first argument is -h or --help. If so, it prints the usage instructions and exits.
  • SEARCH_TERM=$1: This assigns the first argument passed to the script to a variable named SEARCH_TERM.
  • curl "getnews.tech/${SEARCH_TERM}": This uses curl to fetch news from getnews.tech for the specified search term.

Step 3: Make the Script Executable

  1. Change File Permissions: Navigate to the directory containing your script and run:
    chmod +x fetch_news.sh

Step 4: Running the Script

  1. Execute the Script: Run the script by typing:

    ./fetch_news.sh world+cup

    To see the help message, run:

    ./fetch_news.sh --help

Conclusion

You've successfully created a Bash script that fetches and displays news about a specified topic from getnews.tech. This script is a basic example of using Bash to automate tasks like fetching information from the internet. It demonstrates how command-line arguments can be used to make scripts more flexible and interactive. Happy news fetching! 📰

What Can You Do Next 🙏😊

If you liked the article, consider subscribing to Cloudaffle, my YouTube Channel, where I keep posting in-depth tutorials and all edutainment stuff for software developers.

YouTube @cloudaffle