0

I'm trying to check if a folder exists. If it doesn't, I create it.

I have this code:

if [ $(is_dir "$contaniningdir/run") = "NO"]; then
  mkdir "$containingdir/run"
fi

However, I'm getting:

is_dir: command not found

So how what's the correct way of doing this?

bsky
  • 19,326
  • 49
  • 155
  • 270

2 Answers2

3

You should use

if [ ! -d "$DIRECTORY" ]; then
  # your mkdir and other stuff ... 
fi

as per this question/answer.. Another relevant question/answer is here.

One of the comments also mentions an important notice:

One thing to keep in mind: [ ! -d "$DIRECTORY" ] will be true either if $DIRECTORY doesn't exist, or if does exist but isn't a directory.

For more you should probably check that other question's page.

is_dir is a PHP function that you probably mixed with bash unintentionally :)

Community
  • 1
  • 1
trainoasis
  • 6,419
  • 12
  • 51
  • 82
1

bash is capable of checking for the existence of a directory without external commands:

if [ ! -d "${containingdir}/run" ]; then
  mkdir "${containingdir}/run"
fi

! is negation, -d checks if the argument exists and is a directory

Tom Regner
  • 6,856
  • 4
  • 32
  • 47