如果所有命令都有效,是否可以使所有命令获得反馈?


11

有时,当我运行命令时,它不会显示输出,因此我不确定它们是否起作用。如果所有命令都正确运行,是否可以使所有命令获得反馈?或者至少显示他们运行的反馈ID(正确与否)


6
总体思路是:没有反馈意味着它有效。
Rinzwind

1
这不是真的。例如,cryptsetup默认情况下可以跳过一些错误消息。拥有$?您的东西是一件好事PS1。下一步就是添加当前时间,以始终了解命令的时间;)
d33tah

Answers:


11

(我认为,由于您是在Ask Ubuntu中发布的,所以我们可以假设您正在谈论默认的Shell,即Bash。)

在Shell脚本中的Stack Overflow问题中有一个很好的答案:在执行shell命令时回显shell命令(这不仅仅是Ubuntu特定的解决方案)。

您需要做的是使用set命令打开详细或xtrace。

set -o

会给你其中的电流参数进行切换到列表关闭

set -v

或长版版本:

set -o verbose

会变成冗长ON

我想您想要的实际上是xtrace。这不仅会回显您运行的每个命令,还将扩展参数并提供更多反馈。因此,如果我在终端上执行与输入“ hi”一样愚蠢的操作,我将得到我输入内容的回显,以及外壳程序试图执行命令“ hi”的报告/跟踪(请参见下面的屏幕截图) ):

在此处输入图片说明

要启用xtrace:

set -x

要么:

set -o xtrace

要禁用这些参数,您(以直觉方式)调用相同的命令,但用加号+代替破折号或减号,因此,例如:

set +v

会变成冗长OFF,类似:

set +x

会变成X跟踪关闭


有关外壳程序选项的详细指南,请参见第33章。选项,高级Bash脚本指南


1
但是,如果命令正确,它将如何工作?它给出任何输出吗?为命令说whoami >/dev/null
注册用户

是的,当然可以,它会回显您键入的内容以及调用命令时以静默方式调用的命令中涉及的任何其他参数。如果您的意思是,它会打印“ SUCCESS”,那么可悲的是,不,Avinash Raj的答案会做到这一点。
本杰明·R

@PeterMortensen感谢您对我的答案进行了细微的修改。
本杰明·R

13

要检查某个命令是否成功运行,可以使用以下命令检查上一个命令的返回状态(由给出)$?

echo $?

返回状态为0表示命令成功完成,而输出为非零(错误代码)则表示遇到了一些问题或存在错误,并且可以从错误代码中知道类别。Linux和C错误代码在/usr/include/asm-generic/errno-base.h和中定义/usr/include/asm-generic/errno.h

同样在bash中,.bashrc定义了一个别名alert,该别名可用于通知完成状态。您必须将别名附加到命令或命令组合中,如下所示:

some_command --some-switch; alert

您可以将以下代码行添加到~/.bashrc文件中,以显示最后执行的命令的返回状态

# show the return code of last command executed
PS1='${debian_chroot:+($debian_chroot)}\u@\h(lst ret. $(echo $?) ):\w\$ '

~/.bashrc使用您选择的文本编辑器打开文件,然后复制上面的行,将其粘贴到文件中并保存。启动终端的新实例,然后将其运行。或者可以定义一些功能并使用它与PS1像等如下所示。)

一点演示:

hash@precise(lst ret. 0 ):~$ ls -sh someFileThatsNotThere
ls: cannot access someFileThatsNotThere: No such file or directory
hash@precise(lst ret. 2 ):~$ 
hash@precise(lst ret. 2 ):~$ aCommandThatsNot
aCommandThatsNot: command not found
hash@precise(lst ret. 127 ):~$ 
hash@precise(lst ret. 127 ):~$ echo "you should get a lst ret. 0, I believe the system has echo installed :)"
you should get a lst ret. 0, I believe the system has echo installed :)
hash@precise(lst ret. 0 ):~$
hash@precise(lst ret. 0 ):~$ sudo touch /tmp/someTestFile
[sudo] password for hash: 
hash@precise(lst ret. 1 ):~$
hash@precise(lst ret. 1 ):~$ chown $USER:$USER /tmp/someTestFile 
chown: changing ownership of `/tmp/someTestFile': Operation not permitted

只是玩PS1:) ..再多一点,

function showRetStat {
## line1: initiliazing retStat with the return status of the previous command
retStat=$?
## line2: Left padding the return status with spaces. If you prefer the unpadded one, you can just replace
# $retStatFtd in the lines initializing noErrStr and errStr among other possible ways.
retStatFtd=$(sed -e :a -e 's/^.\{1,2\}$/ &/;ta' <<< $retStat)
## lines3&4: Setting the strings to display for a successful and unsuccessful run of previous command
# which we are going to display with the prompt string. Change the strings to display text of your
# choice like you may set noErrStr="yippie!" , errStr="oopsie!" in place of what they're now.
noErrStr="retStat "$retStatFtd" :: PASS ^_^"
errStr="retStat "$retStatFtd" :: FAIL x_x"
## line5: Applying the logic and display the proper string at the prompt. Space padded number i.e. retStatFtd, here,
# worked in the logic, originally I intended to use this for the display while retStat in the conditional
# check; you could make the function one statement less if you want to.
echo "$([ $retStatFtd = 0 ] && echo "$noErrStr" || echo "$errStr")"
}

## Combining the function showRetStat into the prompt string.
PS1='${debian_chroot:+($debian_chroot)}\u@\h($(showRetStat)):\w\$ '

(您可以修改该功能以使其更加精美,就像@gronostaj在其帖子中所做的那样。)


2
我非常喜欢您通过示例扩展的答案。我非常确定OP希望使用xtrace,但就我个人而言,我会发现这对于调试我自己的命令行程序以及更好地理解其他程序很有用。
本杰明·R

1
我建议对返回值进行左填充,以使其长度始终相同。
o0'。

+1用于修改PS1。这是我使用的那个,如果发生错误,则用红色数字表示,如果成功执行上一条命令,则没有其他事情:\[\033[01;41;37m\]${?#0}\[\033[00;01;36m\] \u@\h:\w\[\033[00m\]\$
CarlosCampderrós2014年

1
@rusty是不需要源 ~/.bashrc文件吗?
Avinash Raj 2014年

2
是的,修改PS1很有帮助,而且非常灵活。我^_^对成功表示高兴,x_x对其他任何事情表示红色。
Izkata 2014年

5

您可以更改命令提示符,以在上一个命令退出时显示绿色的勾号(0时),否则显示红色的X。Arch Linux Wiki有一些不错的代码可添加到您的bash.rc

set_prompt () {
    Last_Command=$? # Must come first!
    Blue='\[\e[01;34m\]'
    White='\[\e[01;37m\]'
    Red='\[\e[01;31m\]'
    Green='\[\e[01;32m\]'
    Reset='\[\e[00m\]'
    FancyX='\342\234\227'
    Checkmark='\342\234\223'

    # Add a bright white exit status for the last command
    #PS1="$White\$? "
    # If it was successful, print a green check mark. Otherwise, print
    # a red X.
    if [[ $Last_Command == 0 ]]; then
        PS1+="$Green$Checkmark "
    else
        PS1+="$Red$FancyX "
    fi
    # If root, just print the host in red. Otherwise, print the current user
    # and host in green.
    if [[ $EUID == 0 ]]; then
        PS1+="$Red\\h "
    else
        PS1+="$Green\\u@\\h "
    fi
    # Print the working directory and prompt marker in blue, and reset
    # the text color to the default.
    PS1+="$Blue\\w \\\$$Reset "
}
PROMPT_COMMAND='set_prompt'

(我已经停用实际的错误代码,因为我不喜欢它,如果你想看到确切的代码只是删除#此行:#PS1="$White\$? "

外观如下:

GUI Terminal屏幕截图

tty屏幕截图


2

是的,您可以在终端上执行的每个命令都获得反馈,它的工作原理echo $?是成功完成命令将返回0,失败则返回0以外的任何其他值。

要获取成功或失败反馈,请在~/.bashrc文件中添加以下行。

bind 'RETURN: ";if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;\n"' 

然后使用源~/.bashrc文件使其工作。

source ~/.bashrc

说明:

对于您在终端上执行的每个命令,此;if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;代码将自动绑定到该命令。

例:

$ sudo apt-cache policy firefox;if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;
firefox:
  Installed: 24.0+build1-0ubuntu1
  Candidate: 24.0+build1-0ubuntu1
  Version table:
 *** 24.0+build1-0ubuntu1 0
        500 http://ubuntu.inode.at/ubuntu/ saucy/main amd64 Packages
        100 /var/lib/dpkg/status
SUCCESS

$ suda apt-get update;if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;
No command 'suda' found, did you mean:
 Command 'sudo' from package 'sudo-ldap' (universe)
 Command 'sudo' from package 'sudo' (main)
 suda: command not found
FAILURE

在此处输入图片说明


1
bind 'RETURN: " && echo SUCCESS || echo FAILED \n"'也将执行相同的操作,您无需[[ $? == 0 ]]显式检查。
souravc 2014年

但是,C / Linux标准和与“成功”相对应的英语语法标准将失败。
本杰明·R
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.