djechlin
djechlin

Reputation: 60768

Bash built-in that always fails with specific error code?

I think I can write this myself as

unrollme-dev-dan:~ Dan$ echo 'exit $@' > fail
unrollme-dev-dan:~ Dan$ chmod +x fail
unrollme-dev-dan:~ Dan$ ./fail 42
unrollme-dev-dan:~ Dan$ echo $?
42

Is there a built-in that does this? exit of course will not work because it will exit your current process, not create a child process and exit from that. test is the easiest way I found to simply get 0 or 1 as a return code.

Similar to http://httpstat.us/ I need to unit test specific error codes. This has been surprisingly hard to Google for since most results are to handle errors, not cause them.

Upvotes: 4

Views: 96

Answers (2)

rici
rici

Reputation: 241721

You can easily create a child process and exit from it with a return code:

( exit 42 )

Upvotes: 4

kojiro
kojiro

Reputation: 77107

There does not appear to be any such built in in POSIX. If there's a nonstandard utility, I don't know about it, but you can just compose a trivial shell function, such as

fail() {
  return $(( $1 ))
}

The arithmetic expression guards against non-numeric values. You could write

a=6
fail a

and you'd get an exit status of 6. If you just wrote return $1 you'd get an error from the shell.

Upvotes: 2

Related Questions