Networking

Unix and Linux network configuration. Multiple network interfaces. Bridged NICs. High-availability network configurations.

Applications

Reviews of latest Unix and Linux software. Helpful tips for application support admins. Automating application support.

Data

Disk partitioning, filesystems, directories, and files. Volume management, logical volumes, HA filesystems. Backups and disaster recovery.

Monitoring

Distributed server monitoring. Server performance and capacity planning. Monitoring applications, network status and user activity.

Commands & Shells

Cool Unix shell commands and options. Command-line tools and application. Things every Unix sysadmin needs to know.

Home » Commands & Shells

Handling errors and trapping system calls

Submitted by on December 2, 2005 – 11:20 am 5 Comments

In the course of writing a shell script it is important to consider possible error and unexpected interrupts. Let’s say you wrote an interactive script that allows users to archive old files to free up allocated disk space. The scripts asks the user to specify the directory to archive; The script makes a tarball from that directory and compresses it with gzip; The original files are then deleted from the disk. Here’s the basic example of such a script:

#!/bin/ksh
echo "Enter directory to be archived: c"
read DIR
tar cvf  "${DIR}.tar" "$DIR"
gzip "${DIR}.tar"
rm -r "$DIR"

The script above will work, but it is potentially destructive because it removes the source directory without verifying that tar and gzip operations completed successfully. Let’s rewrite the script to make it a bit more robust:

#!/bin/ksh
echo "Enter directory to be archived: c"
read DIR

# Make sure the directory exists
if [ ! -d "$DIR" ]
then
     echo "Directory $DIR not found."
     exit 1
else
     tar cvf  "${DIR}.tar" "$DIR"

     # If tar completed without errors, then gzip the tar file
     if [ $? -eq 0 ]
     then
          gzip "${DIR}.tar"

           # If gzip completed without errors, then remove the source directory
          if [ $? -eq 0 ]
          then
               rm -r "$DIR"
          else
               if [ -f "${DIR}.tar" ]
               then
                    rm "${DIR}.tar"
               fi
                if [ -f "${DIR}.tar.gz" ]
               then
                    rm "${DIR}.tar.gz"
               fi
               echo "Gzip command failed. Incomplete tar/gz archive removed. You original files are untouched."
               exit 1
          fi
     else
          if [ -f "${DIR}.tar" ]
          then
               rm "${DIR}.tar"
               echo "Tar command failed. Incomplete tar archive removed. You original files are untouched."
               exit 1
          fi
     fi
fi

Now we have a script that is less likely to delete files without archiving them first. This script will also clean up after itself in case if runs into certain types of problems. But there are still conditions this script cannot handle. Imagine that during the tar or gzip operations the user decides he has more important things to do and hits CTRL-C or CTRL- to interrupt or terminate the script. Let’s rewrite the script to make sure we account for such a likely possibility.

#!/bin/ksh
echo "Enter directory to be archived: c"
read DIR

# Make sure the directory exists
if [ ! -d "$DIR" ]
then
     echo "Directory $DIR not found."
     exit 1
else
     trap 'rm "${DIR}.tar"; rm core; exit 1' INT TERM QUIT
     tar cvf  "${DIR}.tar" "$DIR"

     # If tar completed without errors, then gzip the tar file
     if [ $? -eq 0 ]
     then
          trap 'rm "${DIR}.tar"; rm "${DIR}.tar.gz"; rm core; exit 1' INT TERM QUIT
          gzip "${DIR}.tar"

           # If gzip completed without errors, then remove the source directory
          if [ $? -eq 0 ]
          then
               rm -r "$DIR"
          else
               if [ -f "${DIR}.tar" ]
               then
                    rm "${DIR}.tar"
               fi
                if [ -f "${DIR}.tar.gz" ]
               then
                    rm "${DIR}.tar.gz"
               fi
               echo "Gzip command failed. Incomplete tar/gz archive removed. You original files are untouched."
               exit 1
          fi
     else
          if [ -f "${DIR}.tar" ]
          then
               rm "${DIR}.tar"
               echo "Tar command failed. Incomplete tar archive removed. You original files are untouched."
               exit 1
          fi
     fi
fi

Here is the complete list of system calls for Korn shell

Number KSH name Comments
0 EXIT This number does not correspond to a real signal, but the
corresponding trap is executed before script termination.
1 HUP hangup
2 INT The interrupt signal typically is generated using
the DEL or the ^C key
3 QUIT The quit signal is typically generated using the ^[ key.
It is used like the INT signal but explicitly requests
a core dump.
9 KILL cannot be caught or ignored
10 BUS bus error
11 SEGV segmentation violation
13 PIPE generated if there is a pipeline without reader to
terminate the writing process(es)
15 TERM generated to terminate the process gracefully
16 USR1 user defined signal 1
17 USR2 user defined signal 2
DEBUG KSH only: This is no signal, but the
corresponding trap code is executed before each statement
of the script.

Example:

trap 'rm -f "$Tmp" >/dev/null 2>&1' 0
trap "exit 2" 1 2 3 15
Print Friendly, PDF & Email

5 Comments »

  • Daisy pal says:

    i want to do something quite opposite to this, i want to untar the directory and then gunzip the files in that directory

    #!/bin/ksh
    echo “Enter directory to be archived: \c”
    read DIR
    tar xvf “${DIR}”
    gunzip -r “$DIR”

    this is not working for me…….this script is not able to gunzip the files
    Please help.

  • Oilers says:

    Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    If Int(TextBox3.Text) = Int(TextBox1.Text) + Int(TextBox2.Text) Then
    PictureBox1.ImageLocation = “G:Children Programming123Greentick.jpg”

    Else

    PictureBox1.ImageLocation = “G:Children Programming123Newcross.jpg”

    End If
    End Sub

    Basically above is the code is correct the thing is i want to show error message e.g.error Msgbox (“Please enter a value”) when you type abcbb in the textboxes then it should show an error message saying , please enter a numerical value.

    Thanks , i am really working hard….

    Please help me out

  • Jon P says:

    I suspect it has something to do with my Linksys Compact Wireless-G USB Network Adapter with Speedbooster. It only happens when it is plugged in or unplugged but says it’s still connected. My USB is plugged into the front of my disk drive. Not sure how to do some of the things that they tell me to do, I’m not a computer expert.

    When it goes to blue screen it says:

    A problem has been detected and windows has been shut down to prevent damage to your computer.

    If this is the first time you’ve seen this Stop error screen, restart your computer. If the screen appears again, follow these steps:

    Run a system diagnostic utility supplied by your hardware manufacturer. In particular, run a memory check, and check for faulty or mismatched memory. Try changing video adapters.

    Disable or remove any newly installed hardware and drivers. Disable or remove any newly installed software. If you need to use Safe Mode to remove or disable components, restart your computer, press F8 to select Advanced Startup Options, and then select Safe Mode.

    Technical information:
    ***STOP: 0x0000007F, 0x00000008, 0x80042000, 0x00000000, 0x00000000)

    Beginning dump of physical memory
    Physical memory dump complete.
    Contact your system administrator or technical support group for further assistance.
    It lets me use the internet but crashes sometimes. It just bugs me that it crashes. (when I said that it happens when I unplug it or sometimes when it’s plugged in, I meant that I’m on the internet when it crashes. I have Malwarebytes, I think. And I don’t think I have a virus because that would detect it.

  • Malcolm Hudson says:

    I was arrested last year for a misdemeanor drug offense in my home state of GA. I contacted a lawyer because I absolutely could not lose my license due to my driving a company vehicle at work. (license suspension is mandatory for misdemeanor possession in GA) we began the long run through the court system until I finally plead guilty in February.

    I got a lawyer because when I spoke to him, he said he would be able to win the case via illegal search and seizure since they pulled my friend over and didn’t have grounds to cite him with anything and no one in the car provided just cause for searching or questioning.

    Long story short, the judge refused to hear it and my lawyer was still dead set on us winning so his plan was to try once more, and if denied we would take a guilty sentence and then appeal. I agreed with his ‘expertise’ and decided to go that route. First, he calls me on Feb, 2 2011 at 9 am and asks if I am coming to court without any prior notification. I was working an hour away and not only couldn’t leave on a whim but would never make a 9 30 court case. I told him I couldn’t make it and he said he would ‘handle’ it. By handling it, he meant he would allow a bench warrant to be placed for my arrest and nothing more. He called and told me to lay low til the 28th when my next court date was scheduled. I again listened to his advice, then showed up on the 28th. He spoke to the D.A. and took me outside the courtroom to tell me that if I plead guilty to follow through with our appeal plan, my licenses would be suspended indefinitely until the court of appeals was able to sort through my case or I could accept the first offender act, get an ass load of fines, comm service, classes, probation, etc and keep my license. I decided to throw in the towel because my license were literally my livelihood.
    I went back into the court room where I was immediately taken into custody due to my bench warrant (spent 12 HOURS shackled wrists and ankles like I was a dangerous criminal and left with no ability to contact anyone or anything, was then transferred to jail and had to sit for 3 more hours, then finally released). After being taken into custody, I had to walk out (shackled) to plead with a decent amount of humiliation. I plead for the first offender act and got out of jail later that night.

    About two weeks later, the department for driver’s services sent me a letter informing that my license had been suspended for 6 months. I had to quit my job because if stopped for any reason, I would violate probation and absolutely go to jail for driving with no license. I scheduled another court date, went back to court a month later at their earliest opening, refiled to get my sentence corrected and a week later my license were back in order.

    Due to the gravity of the situation, I was unable to receive unemployment benefits, I was unable to drive for a total of 7 weeks and I had zero income to pay mortgage, loans, credit cards, etc.

    I finally have resumed work but I have 2+ months of backed up debt and more piling on with the coming days. Not only do I have 2200 in fines, court fees, probation, classes etc, but I still have my other bills and my new job only pays about half of what my old one pays.

    I was screwed somewhere and I need some help, does anyone have any suggestions? thanks so much!

    also, please don’t reply if you’re just going to tell me drugs are bad and I deserve this, etc.
    I had 2 grams of pot coming home from a party in my honor because I (at 20 yrs old) had just closed on my first home purchase without any financial assistance and I was enjoying life. I am not a deadbeat or a stoner or a drunk. I was having a fun weekend to celebrate something monumental in my life and now I will be fighting a horrible uphill battle to climb out of this horrible situation.

    Thanks for your help!
    Jake
    lets clarify a bit. I am not trying to sue him for losing my case. I am trying to sue him for misfiling my first offender plea. I hate that all the other stuff comes with it, but I would still have a job and my license if he filed my plea correctly and then I would be able to pay for all the non-essential junk I am being dragged through.
    ok guys…. PLEASE READ THIS !!! NOBODY IS ANSWERING THE QUESTION.

    on feb 28th I had two options. these options were:

    1 – – plead guilty (no plea bargain) and lose my license, then follow up with appeals court to possibly overturn sentence.

    2 – – plead first offender act which would not result in my license being suspended at all.

    PLEASE READ THIS

    I know I am responsible for all of this ultimately, but I most definitely would have kept my job and license if my lawyer had filed the correct sentence with the district attorney the first time.

    Again, I want to take action against my lawyer because his mis-filing of my plea caused me to lose my license.

    everyone with me?

  • Hayden says:

    What is difference between bash scripting and shell scripting in LINUX and UNIX? Is it same or different?

Leave a Reply to Daisy pal Cancel reply

%d bloggers like this: