Для того, щоб перевірити , якщо деякі команди успішно працювали або ви не можете перевірити статус повернення , що задається $?, з попередньої команди з:
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 робить у своєму дописі.)