我很困惑。我试图创建一个脚本来自动化一些事情。我有一个函数exitfn()它应该捕获ctrl+c并执行。我这样做是因为,如果你看,在函数下面,这个操作有时会挂起,我只需要运行它。它没有完成,所以我告诉用户按ctrl+c,它应该运行这个函数,但我得到的却是:
/bin/grep:/var/lib/mrtg/cfgs/.cfg: No such file or directory.
我的想法:
- 它是否正确运行第一个命令?
-
我把整个陷阱都用错了吗?
#!/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
谢谢你的时间。
你在脚本中使用了太多的trap
:)
你的代码应该是这样的:
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
一般来说,疏水阀的正确用法是trap "instructions" SIGNAL[S]
。一旦您将这一行放入脚本中,陷阱将对下面的所有指令都有效(前面的那些不会触发陷阱)。
如果您想在退出函数中强制等待perl脚本的执行,只需捕获SIGINT并且不执行任何操作。
关于您的第一个点,是的,thresholdHandler.pl
将运行。但是,如果您按CTRL+C,它将运行2次(一次由常规脚本运行,虽然不完全,因为它被SIGINT中断,一次由exitfn当它被陷阱调用时),具有不同的值(我不知道这是有意的还是复制示例时的简单拼写错误)。