4 ms·
TIL: You can use `echo $?` to get the last process's exit code.
by scudd 6y ago
TIL: You can use `echo $?` to get the last process's exit code.
- enriquto 6y agothis is actually the most useful thing to put in your prompt (much more than your username, the current directory and other redundant stuff), as in PS1='$?\$ '
- chriswarbo 6y agoI used to leave my prompt alone until recently, but was inspired by https://news.ycombinator.com/item?id=26059023 https://news.ycombinator.com/item?id=26059023 to at least conservatively raise my expectations. Now my prompts start with the current UNIX time, coloured red if the previous exit code was non-zero, or green if it was zero. This gives me instant feedback on success/failure, and lets me retroactively see how long a command took (without having to re-run it with `time`).
- enriquto 6y agowouldn't it be more useful to show the time difference? Or maybe only show it in case it is larger than 1 second?
- Izkata 6y agoI do that, if it's over 60 seconds - it's not as straightforward since you also need to use PROMPT_COMMAND, a debug trap, and a variable to store the start time: https://jakemccrary.com/blog/2015/05/03/put-the-last-commands-run-time-in-your-bash-prompt/ https://jakemccrary.com/blog/2015/05/03/put-the-last-command...
- chriswarbo 6y agoDuration and start time can both be useful, and the former can be calculated from the latter as needed. Plus it's easier to implement (stateless) and has consistent alignment (always 10 digits). BTW here's the function I use: ``` showTime() { if [[ "$?" -eq 0 ]] then TIMECOLOR='\e[92m' else TIMECOLOR='\e[91m' fi echo -e "$TIMECOLOR$(date '+%s')\e[0m" } ```
- Noumenon72 6y agoMight be useful but I just spent half an hour trying everything at https://stackoverflow.com/questions/16715103/bash-prompt-with-last-exit-code https://stackoverflow.com/questions/16715103/bash-prompt-wit... on a MacBook Pro and none of it worked.
- LeoPanthera 6y agoMaybe you are not using bash. echo $SHELL to find out.
- JdeBP 6y agoThat's because, as a MacOS user, you are probably using the Z shell, not the Bourne Again shell. Prompt syntax is specific to each individual shell program. One cannot just blindly use a Stack Exchange Q&A that states that it is for "Linux" and "bash" on the Z shell on MacOS, or indeed on the Z shell on a Linux-based operating system for that matter. Or in the C shell. Or in the Korn shell. Or in the Watanabe shell.
- cmehdy 6y agoA good summary of the most frequent things like that: https://stackoverflow.com/a/5163260 https://stackoverflow.com/a/5163260 (Although they're sometimes tricky to use without more careful consideration.. like everything with bash and other shells really..)