检测空命令 [英] Detect empty command

查看:125
本文介绍了检测空命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个PS1

PS1='\n${_:+$? }$ '

下面是一些命令的结果。

Here is the result of a few commands

$ [ 2 = 2 ]

0 $ [ 2 = 3 ]

1 $

1 $

第一行显示没有状态如预期,接下来的两行显示
正确退出code。然而在第3行只输入是pressed,所以我想
状态走开,像1号线。我怎样才能做到这一点?

The first line shows no status as expected, and the next two lines show the correct exit code. However on line 3 only Enter was pressed, so I would like the status to go away, like line 1. How can I do this?

推荐答案

下面是一个有趣的,很简单的可能性:它使用的 \\#转义序列 PS1 连同参数扩展(和Bash的方式扩大其提示)。

Here's a funny, very simple possibility: it uses the \# escape sequence of PS1 together with parameter expansions (and the way Bash expands its prompt).

转义序列 \\#扩展到要执行的命令的命令数量。这是每一个指令实际执行时间递增。试试吧:

The escape sequence \# expands to the command number of the command to be executed. This is incremented each time a command has actually been executed. Try it:

$ PS1='\# $ '
2 $ echo hello
hello
3 $ # this is a comment
3 $
3 $    echo hello
hello
4 $

现在,每一个提示是要显示的时间,猛砸首先扩展在 PS1 中发现的转义序列,则(提供的shell选项 promptvars 设置,这是默认值),这个字符串通过参数扩展,命令替换,算术扩展和引用删除扩展。

Now, each time a prompt is to be displayed, Bash first expands the escape sequences found in PS1, then (provided the shell option promptvars is set, which is the default), this string is expanded via parameter expansion, command substitution, arithmetic expansion, and quote removal.

诀窍是那么有一个数组,将有 K 的个场集(空字符串)每当( K 的-1)个命令被执行。然后,使用适当的参数扩展,我们就可以在这些字段设置为检测,如果现场没有设置为显示previous命令的返回code。如果你想调用这个数组 __ cmdnbary ,只是做:

The trick is then to have an array that will have the k-th field set (to the empty string) whenever the (k-1)-th command is executed. Then, using appropriate parameter expansions, we'll be able to detect when these fields are set and to display the return code of the previous command if the field isn't set. If you want to call this array __cmdnbary, just do:

PS1='\n${__cmdnbary[\#]-$? }${__cmdnbary[\#]=}\$ '

查看:

$ PS1='\n${__cmdnbary[\#]-$? }${__cmdnbary[\#]=}\$ '

0 $ [ 2 = 3 ]

1 $ 

$ # it seems that it works

$     echo "it works"
it works

0 $


要晋级简短的回答挑战:


To qualify for the shortest answer challenge:

PS1='\n${a[\#]-$? }${a[\#]=}$ '

这是31个字符。

不要使用这个,当然,如 A 是太微不足道了名;同时, \\ $ 可能比 $ 更好。

Don't use this, of course, as a is a too trivial name; also, \$ might be better than $.

好像你不喜欢,最初的提示符为 0 $ ;你可以很容易通过适当地初始化数组 __ cmdnbary 修改一下:你会把在配置文件中这样的地方:

Seems you don't like that the initial prompt is 0 $; you can very easily modify this by initializing the array __cmdnbary appropriately: you'll put this somewhere in your configuration file:

__cmdnbary=( '' '' ) # Initialize the field 1!
PS1='\n${__cmdnbary[\#]-$? }${__cmdnbary[\#]=}\$ '

这篇关于检测空命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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