1

Is there a way to make bash warn if a variable is undefined but prevent script execution from aborting? I'm looking for something similar to set -u, except that set -u aborts execution and I would like the script to warn, but continue execution when it finds undefined variables. I know I can check whether a variable is set , but my scripts have hundred of variables and I'm looking for a solution that avoids checking variables one by one.

mauroformigoni
  • 129
  • 1
  • 8
  • 1
    [ShellCheck](https://www.shellcheck.net/) can tell you before you run the script. – Benjamin W. Sep 26 '22 at 14:10
  • What's your intent in warning about unset variables? I don't think there's a simple runtime option to do this without aborting but depending on your goal maybe there's another solution. – tjm3772 Sep 26 '22 at 15:33
  • @tjm3772 my script is scheduled to run overnight, and it makes reference to variables that are defined on other files. My intent in warning is that I can periodically check log of execution and know if my script tried to use any undefined variable so that I can fix any typo on the script or define the variable properly. – mauroformigoni Sep 26 '22 at 16:46

1 Answers1

3

You can do it like this:

$ cat /tmp/q.sh
#!/bin/bash

set -u

echo 1
echo $2
echo 3

$ bash --norc --noprofile --noediting -i /tmp/q.sh
1
bash: $2: unbound variable
3

That is, force interactive mode (-i) when running the script, which prevents bash from aborting with set -u, but you have to also use --norc --noprofile --noediting (maybe some things more?), to make it behave more like a non-interactive shell.

I can't tell if this is expected or unexpected behavior, though (it doesn't work when using -c). Works on versions 4.2.46(2)-release (Oracle Linux 7), 4.1.2(1)-release (Oracle Linux 6) and 5.1.16(1)-release (Arch Linux).

spuk
  • 166
  • 4