我需要知道是否可以使用 ESC
或 ENTER
等键来中断 bash 脚本?通过发送 SIGINT/CTRL + C
我可以做到,但是由于某些原因(检查最后一行的注释)我不能使用 CTRL +C
。所以我需要有一些自定义方法来引起中断。
换句话说:在下面的脚本中,cleanup
函数在按下 CTRL + C
时被调用。现在需要修改此行为,以便在按下 ENTER
或 ESC
等键时调用 cleanup
函数。
cleanup() {
#do cleanup and exit
echo "Cleaning up..."
exit;
}
echo "Please enter your input:"
read input
while true
do
echo "This is some other info MERGED with user input in loop + $input"
sleep 2;
echo "[Press CTRL C to exit...]"
trap 'cleanup' SIGINT
done
查询:
- 是否可以使用自定义键在 bash 中引起中断?
- 如果可能,如何实现?
注意事项:
原因:此脚本是从另一个具有自己的陷阱处理的 C++ 程序调用的。所以这个脚本的陷阱处理与父程序冲突,最终导致终端挂起。在我的组织中,该程序的代码已被卡住,因此我无法更改其行为。我只需要调整这个子脚本。
最佳答案
这是一个肮脏的把戏,它可以很好地完成我的工作。 read
和case
语句选项是关键。在这里,我对 read
命令进行了超时处理,以便 true 继续执行,除非按下 esc
或 enter
。
cleanup() {
#do cleanup and exit
echo "Cleaning up..."
exit;
}
exitFunction()
{
echo "Exit function has been called..."
exit 0;
}
mainFunction()
{
while true
do
echo "This is some other info MERGED with user input in loop"
IFS=''
read -s -N 1 -t 2 -p "Press ESC TO EXIT or ENTER for cleanup" input
case $input in
$'\x0a' ) cleanup; break;;
$'\e' ) exitFunction;break;;
* ) main;break;;
esac
done
}
mainFunction
关于linux - 通过 ENTER 或 ESC 等键在 bash 中创建中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44039963/