SIGINT取消bash脚本中的读取? [英] SIGINT to cancel read in bash script?

查看:46
本文介绍了SIGINT取消bash脚本中的读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个bash包装器,以学习一些脚本编写概念.这个想法是用bash编写脚本,并在登录时将其设置为用户的shell.

I'm writting a bash wrapper to learn some scripting concepts. The idea is to write a script in bash and set it as a user's shell at login.

我做了一个while循环,以读取 s和 eval 用户的输入,然后注意到,每当用户键入 CTRL + C 时,脚本中止,因此用户会话结束.

I made a while loop that reads and evals user's input, and then noticed that, whenever user typed CTRL + C, the script aborted so the user session ends.

为避免这种情况,我困了 SIGINT ,在陷阱中什么也不做.

To avoid this, I trapped SIGINT, doing nothing in the trap.

现在,问题是当您在命令的一半输入 CTRL + C 时,它不会像在bash上一样被取消-它只是忽略 CTRL + C.

Now, the problem is that when you type CTRL + C at half of a command, it doesn't get cancelled as one would do on bash - it just ignores CTRL + C.

因此,如果我输入 ping stockoverf ^ Cping stackoverflow.com ,则会得到 ping stockoverfping stackoverflow.com 而不是 ping stackoverflow.com 我想要的.

So, if I type ping stockoverf^Cping stackoverflow.com, I get ping stockoverfping stackoverflow.com instead of the ping stackoverflow.com that I wanted.

有什么办法吗?

#!/bin/bash

# let's trap SIGINT (CTRL + C)
trap "" SIGINT

while true
do
    read -e -p "$USER - SHIELD: `pwd`> " command
    history -s $command
    eval $command
done

推荐答案

您可以使用xdotool之类的工具发送Ctrl-A(行首)Ctrl-K(行尾删除)返回(清理行)

You could use a tool like xdotool to send Ctrl-A (begin-of-line) Ctrl-K (delete-to-end-of-line) Return (to cleanup the line)

#!/bin/bash
trap "xdotool key Ctrl+A Ctrl+k Return" SIGINT;
unset command
while [ "$command" != "quit" ] ;do
    eval $command
    read -e -p "$USER - SHIELD: `pwd`> " command
  done
trap SIGINT

但是我强烈邀请您加入rtfm ...在寻找``debug''关键字时...

But I strongly invite you to rtfm... In searching for ``debug'' keyword...

man -Pless\ +/debug bash

这篇关于SIGINT取消bash脚本中的读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆