I want to check if the environment variable MY_DIR or its containing path doesn't exist.
Can anybody see what I'm doing wrong?
#!/bin/bash
# If $MY_DIR or its containing path doesn't exist
if [ ! $(env | grep -q ^MY_DIR=) ] || [ ! -d "$MY_DIR" ]; then
echo "not existing"
# set it
export MY_DIR="$PWD"
fi
Since the empty string cannot name an existing directory, you don't need to worry if MY_DIR is set or not; just check if its (possibly nonexistent) value names a directory.
if [[ ! -d $MY_DIR ]]; then
export MY_DIR=$PWD
fi
There's also no need to check specifically if MY_DIR is in the environment. While it is possible to have a shell variable that is not an environment variable, it is not possible to have an environment variable that is not also a shell variable[0], nor is it possible to have a shell variable with the same name as an environment variable but a different value (an environment variable is simply a shell variable with its export attribute set.)
[0] OK, technically you could inherit an environment variable whose name is not a valid shell identifier. Let's just ignore those, shall we? :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With