Exemple de script bash regroupant des bonnes pratiques
Source : Advanced Scripting Techniques in Linux Shell Scripting - DEV Community.
# A script to scrape a website and extract data
#!/bin/bash
# Define a log function
log() {
echo "[INFO] $1"
}
# Define a cleanup function
cleanup() {
log "Cleaning up temporary files..."
rm -f /tmp/*.html
}
# Trap the EXIT signal and call the cleanup function
trap cleanup EXIT
# Check if curl is installed
log "Checking if curl is installed..."
if ! command -v curl &> /dev/null; then
log "curl is not installed. Exiting."
exit 1
fi
# Download the website
log "Downloading the website..."
curl -s -o /tmp/website.html https://example.com
# Check if the download was successful
log "Checking if the download was successful..."
if [ $? -ne 0 ]; then
log "An error occurred while downloading the website. Exiting."
exit 1
fi
# Extract the data
log "Extracting the data..."
grep -o '<h1>.*</h1>' /tmp/website.html | sed 's/<[^>]*>//g' > /tmp/data.txt
# Check if the extraction was successful
log "Checking if the extraction was successful..."
if [ $? -ne 0 ]; then
log "An error occurred while extracting the data. Exiting."
exit 1
fi
# Display the data
log "Displaying the data..."
cat /tmp/data.txt
# Exit with success
log "Script completed successfully."
exit 0
Pas de commentaires