0
0
Bash Scriptingscripting~5 mins

HTTP requests with curl in scripts in Bash Scripting

Choose your learning style9 modes available
Introduction

curl lets you talk to websites or servers from your script. You can get or send data easily.

Check if a website is online by requesting its homepage.
Download a file or data from the internet automatically.
Send data to a web service, like submitting a form or API call.
Test if an API is working by making requests from your script.
Automate repetitive web tasks without opening a browser.
Syntax
Bash Scripting
curl [options] URL

Replace URL with the web address you want to access.

Options change what curl does, like -X to set request type or -d to send data.

Examples
Simple GET request to fetch the homepage of example.com.
Bash Scripting
curl https://example.com
Send a POST request with data name=John to a form URL.
Bash Scripting
curl -X POST -d "name=John" https://example.com/form
Fetch only the headers from the server, not the full page.
Bash Scripting
curl -I https://example.com
Download a file and save it locally as file.txt.
Bash Scripting
curl -o file.txt https://example.com/data.txt
Sample Program

This script uses curl to silently check the HTTP status code of a website. If the code is 200, it means the site is reachable.

Bash Scripting
#!/bin/bash

# Simple script to check if a website is reachable
URL="https://example.com"

response=$(curl -s -o /dev/null -w "%{http_code}" "$URL")

if [ "$response" -eq 200 ]; then
  echo "Website is reachable with status code 200."
else
  echo "Website returned status code $response."
fi
OutputSuccess
Important Notes

Use -s to make curl silent so it doesn't print progress.

The -w "%{http_code}" option tells curl to output the HTTP status code.

Redirect output to /dev/null with -o /dev/null if you only want the status code.

Summary

curl lets scripts communicate with websites easily.

You can send GET, POST, and other HTTP requests with options.

Use curl in scripts to automate web checks and data transfers.