我有这个正是我想要的方式。
但是我可以弄清楚如何捕获Ctrl+ C,这样如果我想提前结束脚本,它可以重新启用挂起和休眠模式。
我查看了其他关于捕获Ctrl+的讨论C,但没有发现任何帮助。
谢谢。
# TimerInTerminal.sh
# To prevent your Linux system from suspending or going into hibernation, you need to disable the following systemd targets:
# sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
# To re-enable the suspend and hibernation modes, run the command:
# sudo systemctl unmask sleep.target suspend.target hibernate.target hybrid-sleep.target
soundfile="/usr/share/sounds/My_Sounds/Electronic_Chime.wav"
# Stop computer from sleeping while timer is running
# prevent your Linux system from suspending or going into hibernation
sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
# This allows supend ?
#trap "echo marlin | sudo -S systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target" INT EXIT
if [ $# -eq 1 ]
then
DURATION="$1"
else
read -r -p "Timer for how many minutes?( for fractional, use decimal notation , 0.5==30s, 1.25==75s etc) : " DURATION
read -r -p "Enter text to display at the end of the timer : " n1
fi
DURATION=$(echo "$DURATION * 60 / 1" | bc) # lets us deal with fractional inputs
START=$(date +%s) # only do this once (anchor's the time)
countdown () {
NOW=$(date +%s) # Get time now in seconds
DIF=$((NOW - START)) # Compute diff in seconds
ELAPSE=$((DURATION - DIF)) # Compute elapsed time in seconds
MINS=$((ELAPSE / 60)) # Convert to minutes... (dumps remainder from division)
SECS=$((ELAPSE - (MINS*60))) # ... and seconds
#banner "$MINS:$SECS"
echo "$MINS:$SECS"
sleep "$1"
}
while true
do
clear
countdown 0 # calc time remaining
if [ $MINS -le 0 ]
then
# Blink screen
while [ $SECS -gt 0 ]
do
clear # Flash on
#setterm -term linux -back red -fore white
countdown 0.5
clear # Flash off
#setterm -term linux -default
countdown 0.5
done # End for loop
setterm -term linux -default
clear
break # time has expired lets get out of here
else
countdown 1
fi
done
echo $n1
amixer -D pulse sset Master 30% > /dev/null 2>&1
# Play a sound
cvlc --play-and-exit "$soundfile" > /dev/null 2>&1
# To re-enable the suspend and hibernation modes, run the command:
echo marlin | sudo -S systemctl unmask sleep.target suspend.target hibernate.target hybrid-sleep.target
这行得通。我不会在 ctrl_c 中插入我的整个代码,看看会发生什么。
#!/bin/bash
# trap ctrl-c and call ctrl_c()
trap ctrl_c INT
function ctrl_c() {
echo "** Trapped CTRL-C"
echo System will now have suspension/hibernation halted.
# prevent your Linux system from suspending or going into hibernation
sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
sleep 10
}
ctrl_c
以下是如何
CTRL+C
在脚本中捕获 。您不会调用该ctrl_c
函数,因为当您按键盘上的CTRL+时会调用该函数。C我添加了一个exit 0
,以便它在捕获 后退出脚本CTRL+C
并停止循环遍历for .. loop
.例子:
在您的脚本案例中,您可以执行以下操作: