Bash – Escaping special characters while sourcing file in bash

bashshell-scripting

I've written a script that sources a bash shell fragment. The shell fragment is supposed to be a kind of configuration file, basically it's a bunch of bash variable.

The issue here is when some of those string variable contain characters that should be escaped. As they aren't escape, the script might faill later on or have undesired behavior.

At the moment, my script is validating the shell fragment (the configuration file) bash syntax (bash -n) but if any charachter is to be escaped, that won't be detected.

So, I would like either to auto-escape sensitive character or, at least, detect their are some so I can display an error and exit.

Any idea how could I achieve that?

Best Answer

The $? variable is your friend. It contains the return status of the most recently executed command, including bash built-in functions.

$ /bin/false
$ echo $?
1
$ /bin/true
$ echo $?
0
$ echo 'FOO="bar' > atest
$ . atest
-bash: atest: line 1: unexpected EOF while looking for matching `"'
-bash: atest: line 2: syntax error: unexpected end of file
$ echo $?
1

Keep in mind that it only returns the status of the most recent command. If you need to run an additional command before performing your error test, you need to immediately assign it to a variable like so:

$ /bin/false
$ MYRETURN=$?
$ /bin/true
$ echo $?
0
$ echo $MYRETURN
1