3 ms·
> It doesn’t work for everything. For example, I have a boop command (which I mentioned above) that needs access to the previous command’s exit status—as far as
by yakshaving_jgt 4y ago
> It doesn’t work for everything. For example, I have a boop command (which I mentioned above) that needs access to the previous command’s exit status—as far as I know, that’s impossible with a script.
I got nerd-sniped by this. I can't see any reason why this wouldn't work. I tested this myself by writing a script called show-error.sh:
#!/bin/bash
echo $?
And then I ran
$(exit 5)
. ./show-error.sh
And this outputs
5
- faho 4y agoWell, yeah, if you source the file (for which `.` is a shortcut) it runs in the current shell so the environment is intact. If you just run it it won't work. So instead of running `boop` you would always have to `source boop` or `. boop`. A function or alias you could just run like normal. (and `export ?` complains about ? being an invalid identifier in bash, in zsh `export "?"` apparently "works", but will reset it before you get a chance to print it in another process)
- NegativeLatency 4y agoYou could also pass the exit status into the program being called
- SuchAnonMuchWow 4y agothis only works because you are sourcing the file, and not just executing it: $(exit 5) ./show_error.sh outputs 0. Sourcing the file is the same as copying and pasting its content into the current shell. It is designed to allow this kind of things (accessing the caller execution context). But it is not what we usually call a script precisely because of this.
- throwaway41232 4y agoI cant really check this right now but doesnt $(exit 5) just spawn a subshell which exits with 5 which is visible by the parent script you just source your show-error.sh in? Try to subshell the source too like (. ./show-error.sh)