I can find plenty of information about how to assign the exit code of a script to av variable, but I want to do the opposite: use the value of a variable (defined within a script) as the exit code of the script.

For example, I have a script that couunts the number of open files on a specific file system (plus a bunch of other stuff). I want the exit code of the script to be the number of open files, so essentially:


OPENFILES=`lsof /filesystem | wc -l`


So after the script exits, 'echo $?' will give me the value of $OPENFILES that was defined in the script.

I've tried various permutations of using quotes, parentheses, etc, but come up empty. I feel like what I'm trying to do is either impossible, or so blindingly obvious that I'm overlooking it...

  • 3
    Should work other than you can only exit up to 255.
    – jesse_b
    May 4, 2018 at 18:04
  • That's my problem, then! The values I'm working with are in the thousands when things are "working as expected", and reach a million just before everything goes all to hell (which is the reason for the exercise). I suppose I can just write the value to a file and grab it from there...
    – gfd
    May 4, 2018 at 18:05

2 Answers 2


You can't really use the exit code for what you want, not least because the exit code is an integer between 0 and 255. What behavior would you want if there were 783 open files?

Also, such usage is fundamentally broken in that you are positing an exit code other than zero not being an error condition, which is not remotely standards-compliant.

  • Thanks. I suspected the answer was going to be the "so blindingly obvious..." one. I completely forgot about the 255 max for exit codes. As for the "standards-compliant" aspect, I really wasn't at all worried about that, as we're trying to hack together a solution to monitor an ongoing issue...one of those "sometime in the next fifteen minutes would be great, thanks" sort of things. Hopefully whatever I come up with will be a very temporary solution (though we all know how that tends to go).
    – gfd
    May 4, 2018 at 18:13

You don't need to write to a file. Just have the script output the wc results

lsof /filesystem | wc -l

and then capture the result with


If your script is not more complicated than this, just add this to your ~/.bashrc

alias openfiles='lsof /filesystem | wc -l'

and then

n=$(openfiles); echo $n

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .