问题描述:

I'm at a loss here. I'm trying to create a script to automate some things. I have a function exitfn() it is supposed to catch the ctrl+c and execute. I do this because, if you look, below the function this operation sometimes hangs and I only need to run it. It does not finish so I tell the ask the user to hit ctrl+c and it should run the function but instead I get back:

/bin/grep: /var/lib/mrtg/cfgs/ .cfg: No such file or directory.

My thoughts:

  • Is it even running the first comman correctly?
  • Am I using the whole trap thing wrong?

    #!/bin/bash

    echo "Enter the name of the device: > "

    read dName

    echo "Now enter device type [cpu, ram, : > "

    read dType

    echo "Enter the devices actual value with % symbol: > "

    read aValue

    echo "Enter the desired threshold with % symbol: > "

    read dValue

    echo "Grounding..."

    n=`locate thresholdHandler.pl`

    cd ${n%thresholdHandler.pl}

    echo "Hit Ctrl+C to continue......"

    exitfn() {

    trap SIGINT

    echo;

    echo "Running second command, wait 3 seconds"

    sleep 3

    ./thresholdHandler.pl output above $dname.$dType $dValue $aValue

    echo "Complete"

    exit

    }

    trap "exitfn" INT

    ./thresholdHandler.pl output above $dName.$dType $aValue $dValue

    sleep 10

    trap SIGINT

Thank You for your time.

网友答案:

You use trap way too much in your script :)

Your code should look like this :

echo "Hit Ctrl+C to continue......"

exitfn() {
    trap "" SIGINT    #we trap any further ctrl + c and force execution of exitfn
    echo; 
        echo "Running second command, wait 3 seconds"  
        sleep 3
        ./thresholdHandler.pl output above $dName.$dType $dValue $aValue
        echo "Complete"
    exit 0
}

trap "exitfn" SIGINT    #here, only ctrl+c is trapped. Add more signals here if needed
./thresholdHandler.pl output above $dName.$dType $aValue $dValue
sleep 10

Generally speaking, the correct usage of trap is trap "instructions" SIGNAL[S]. Once you put that line in your script, the trap will be active for all the instructions below (the ones before won't trigger your trap).

If you want to force-wait the execution of your perl script in your exit function, just trap the SIGINT and execute nothing.

Concerning your 1st point, yes, thresholdHandler.pl will be run. However, it will be run 2 times if you hit CTRL+C (once by the regular script, though not fully as it is interupted by SIGINT, and once by the exitfn when it is called by the trap), with different values (I don't know if this is intended or a simple typo in copying the exmaple).

相关阅读:
Top