Question

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
Was it helpful?

Solution

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? :)

OTHER TIPS

I think that it can be made with this code:

if [[ ! -d "$MY_DIR" ]]; then
    export MY_DIR="$PWD"
fi

Or with a one-liner:

[[ ! -d "$MY_DIR" ]] && export MY_DIR="$PWD" || echo "MY_DIR already set"

The above code echoes a message saying when is already set, if is not needed you can try with this:

[[ ! -d "$MY_DIR" ]] && export MY_DIR="$PWD"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top