r/ProgrammerTIL • u/GrehgyHils • Jul 05 '18
Other Language [Other] TIL that the variable `$?`, in a terminal, contains the exit status of the last command ran.
So you can
```
$ ./some_script.sh
$ echo $?
```
to see the exit status of that `some_script.sh`
110
Upvotes
29
u/[deleted] Jul 05 '18 edited Jul 05 '18
Another slightly less-known one is
!$, which contains the lastargumentword of the last command.EDIT:
If you want the actual last argument (i.e. before redirections and whatnot), you want
$_.6
u/javawag Jul 05 '18
Also,
!!gives you the last command you entered. This is useful, for example:*sigh*
:D
3
u/markasoftware Jul 05 '18
There is a
BashFlair for posts like this.2
u/smikims Oct 26 '18
And
??is the PID of the shell you're in. Not useful all the time but I've been doing some work lately that pokes around procfs and it's a good example process to pick for that since you know it'll stick around.3
u/PrincessRTFM Jul 05 '18
You can also customize your prompt to show the last error. In fact, if you have a hook to execute code (usually a function) before printing the prompt (I know bash and zsh do, because I used/am using (respectively) that feature), then you can save it to a temporary variable, and do some flow-control to change the output depending on it. For example, my old bash prompt would display the exit code in green if zero and red if not.
5
u/tevert Jul 05 '18
On windows, it's %ERRORLEVEL% in DOS and $LastExitCode in Powershell.
1
u/rjsberry Jul 06 '18
This is
$statusin fish shell.0
u/color32 Jul 07 '18
this is like the first thing you learn in bash or sh programming. Go read a basic guide to bash and sh.