0

If there a way to affect the '?' variable in bash?

For a regular variable, it is possible to just use FOO=bar, thus 'echo $FOO' will output bar, but for some reason, it is not working with the '?' variable. I have found two workaround but they are quite unsatisfactory.

First, it is possible to use true and false that will set $? to respectively 0 and 1.

#! /bin/bash
echo $?
true
echo $?
false
echo $?

This will output xxx, 0, 1. This workaround is limited, because it only allow to affect the values 0 and 1.

Then, it is possible to write some code in C (or other) that will just return the value in parameter via exit and then call this function. Example :

#! /bin/bash
rm foo.c
touch foo.c
echo "#include <stdio.h>" >> foo.c
echo "#include <stdlib.h>" >> foo.c
echo "int main(int argc, char **argv)" >> foo.c
echo "{" >> foo.c
echo "    return atoi(argv[1]);" >> foo.c
echo "}" >> foo.c
gcc -o foo foo.c
./foo 42
echo $?

That will output 42. Even though it works, it is pretty nasty for doing something so simple, not to mention that this is only a simplified version without all the checkings that would have to be done in order to be sure not to overwrite anything. In addition, this require gcc to be present on the system.

Richard
  • 992
  • 1
  • 11
  • 27

2 Answers2

2

There's no need to involve C at all if you just want to set the most recent return code (although I'm wondering why you're trying to do this). A simple shell function is sufficient:

ret() { return $1; }

Call it like ret 42.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • Well, this is truly simpler than my solution... thanks. By any chance do you know why bash doesn't allow you to set this variable like any other? – Richard Feb 19 '16 at 09:37
  • @Richard the $? is a buildin variable that stores exitcode of the last command that was executed. – hetepeperfan Feb 19 '16 at 09:49
0

Of course you know that '$?' holds the exit code of the last executed command. If the command is your own written executable, then '$?' holds its exit code. The default value is 0 (success).

To sum up: use exit in your own scripts.

$ ls
$ echo $?
0
$ echo '#!/bin.bash' > script1.sh && chmod u+x script1.sh
$ ./script1.sh
$ echo $?
0
$ echo -e '#!/bin.bash\nexit 42' > script2.sh && chmod u+x script2.sh
$ ./script2.sh
$ echo $?
42

Also, have a look at Return value in bash script

Community
  • 1
  • 1
alleen1
  • 418
  • 6
  • 14