Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does marking a variable readonly mask the exit status in bash?

Tags:

bash

I'm confused by this output:

$ readonly foo=`exit 1`
$ echo $?
0
$ bar=`exit 1`
$ echo $?
1

Why does the readonly make a difference?

like image 328
Dominic Rodger Avatar asked Sep 19 '25 01:09

Dominic Rodger


1 Answers

readonly is a function call and is entered after the exit 1 subshell has finished.

Your script now returns the return value of readonly.

A one-liner that retains the return code semantics could be

foo=`exit 1` ; RC=$? ; readonly foo ; `exit $RC`
like image 60
Felix Frank Avatar answered Sep 20 '25 16:09

Felix Frank