0

I want a bash script that will set several environment variables (userid, password, token) to some default values if they don't already exist. The existence test works on the CLI but not in the script.

magilla@raspberrypi:~ $ ps -p $$
    PID TTY          TIME CMD
   3005 pts/0    00:00:05 bash
magilla@raspberrypi:~ $ echo "${BASH_VERSION}"
5.1.4(1)-release

magilla@raspberrypi:~ $ env | grep var
magilla@raspberrypi:~ $ [[ -v var ]] && echo "\${var} not defined" || echo "\${var} is defined"
${var} not defined

magilla@raspberrypi:~ $ cat myscript
#!/bin/bash
[[ -v var ]] && echo "\${var} not defined" || echo "\${var} is defined"
magilla@raspberrypi:~ $ bash myscript
${var} is defined
magilla@raspberrypi:~ $ bash < myscript
${var} is defined
0

1 Answer 1

1

Apparently var is set in your interactive shell (it's not in the environment though). Then [[ -v var ]] returns success and echo "\${var} not defined" is executed.

You see not defined because the logic of your code is wrong.

In the script var is not set, [[ -v var ]] returns failure and echo "\${var} is defined" is executed.

You see is defined because again the logic is wrong. The following logic makes sense:

[[ -v var ]] && echo "\${var} is defined" || echo "\${var} not defined"

It's opposite to the logic of your code.

3
  • Ok, thanks! For what it's worth I got this code from this link. I see that the logic is reversed. The env | grep checked the environment. How do I check that var is set in the interactive shell?
    – Magilla
    Commented Jun 27, 2022 at 12:13
  • Also, I read elsewhere that passing ${var} rather than var to -v would not be right, as it would expand that possibly-unset variable before the test operator sees it; so it has to be part of that operator's task to inspect that variable, pointed to by its name, and tell whether it is set. In short, -z tests a value and –v tests a name. The link shows ${var} so perhaps there are 2 things wrong over there?
    – Magilla
    Commented Jun 27, 2022 at 12:23
  • set with no arguments prints out all the env vars, shell vars and functions. Commented Jun 27, 2022 at 13:55

You must log in to answer this question.

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