Reputation: 390
Say I have a bash script which counts something, and I'd like the return code for that script to be the number of things that were counted. Is there a way to do this?
I'm aware that bash variables are technically typeless, but act "string-like", and exit
cannot take a "string" as an argument.
I'm also aware of the fact that bash return codes can only be within the range of 0-255, and am willing to live with the consequences of roll-over i.e. counting 256 things will give a return code of 0.
I think I'm looking for a program or other bash built-in that would, when given a variable, return a code which had a numerical value equal to the "string-like" number that was stored in that variable, which would allow me to do something like so:
#/bin/bash
$count=0
count_stuff
command_to_turn_var_into_return_code $count
Upvotes: 0
Views: 226
Reputation: 183381
Well, yes — you can just write exit "$count"
. But in your case, you shouldn't do this. It's not how exit statuses are intended to be used, so it will cause problems in its interactions with things that understand exit statuses in general.
Instead, you should print your result (using echo
or printf
), so that it can be captured by command substitution, piped to other commands, etc.
I'm aware that […] exit cannot take a "string" as an argument.
This is simply not true. The exit status has to be a number, of course, but there's no problem with the number being in string form. (Arguments to Bash commands are always in string form.)
Upvotes: 2