Introduction
Use trap to run cleanup code automatically when your script ends or is interrupted. This helps keep things tidy and safe.
trap 'commands_to_run' signalstrap 'echo Cleanup done' EXITtrap 'rm -f /tmp/tempfile' EXITtrap 'echo Interrupted; exit' INT#!/bin/bash # Create a temp file tempfile="/tmp/mytempfile.txt" touch "$tempfile" echo "Temp file created: $tempfile" # Define cleanup function cleanup() { echo "Cleaning up..." rm -f "$tempfile" echo "Cleanup done." } # Set trap to call cleanup on script exit trap cleanup EXIT # Simulate work echo "Doing some work..." sleep 2 echo "Script finished."
trap in a bash script?trap command is designed to catch signals or script exit events and run commands in response.trap. Only To run specific commands when the script exits or receives signals correctly describes its purpose.cleanup function on script exit using trap?EXIT. trap EXIT cleanup places the signal before the command (wrong order). Options C and D use incorrect keywords like 'on'.#!/bin/bash
cleanup() {
echo "Cleaning up temp files"
}
trap 'cleanup' EXIT
echo "Script is running"
cleanup function runs, printing "Cleaning up temp files" after the first echo.#!/bin/bash
trap cleanup EXIT
cleanup() {
echo "Cleaning up"
}cleanup, quotes are not required around the command in trap.cleanup after trap is allowed because bash processes function definitions before executing traps. EXIT is valid. No syntax errors present./tmp/mytempfile is deleted when your bash script exits, even if interrupted. Which trap command correctly achieves this?Pass the test and this pattern moves unknown