Facebook X (Twitter) Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook X (Twitter) Instagram
    TecAdmin
    You are at:Home»Programming»Bash Shell»How to run a command on bash script exits

    How to run a command on bash script exits

    By RahulAugust 2, 20221 Min Read

    Shell scripts are handy for automating tasks like backup databases, clearing log files, etc. You need to perform some tasks when the script finishes the execution. No matter at which stage the script is finished.

    For example, a script that clears the log files from the system. The script first checks the size of the log file, if the log file size is lower than the specified size, the script exits. In that case, you still want to run a block of code.

    To do this, we can use the trap command to catch the EXIT signal and execute a command or function. Below is the sample shell script to run a function or command on shell script exit.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/usr/bin/env bash
     
    on_exit(){
      echo "Your script ended now"
    }
     
    trap 'on_exit' EXIT
     
    echo "Hello world"

    Run the above script and see the results

    Output
    Hello world Your script ended now

    Hope, this quick how-to guide helps you to improve your shell script writing skills.

    bash command shell script trap
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    An Introduction to Bash Variables

    An Introduction to Bash Variables

    Bash LOCAL and GLOBAL Variables

    Bash LOCAL and GLOBAL Variables

    Bash Script to Reverse a Number

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Difference Between Full Virtualization vs Paravirtualization
    • Virtualization vs. Containerization: A Comparative Analysis
    • Using .env Files in Django
    • Using .env File in FastAPI
    • Setting Up Email Notifications for Django Error Reporting
    Facebook X (Twitter) Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.