Bash – Executing a command within `if` statement and on success perform further steps

bashdirectoryfunctionmkdir

I was trying to execute a program which will create a directory on the basis of a complete path provided to it from the prompt and, if the directory already exists it will return an error (for "directory already exists") and ask again for the name in a recursive function.

Here it is what I tried: let us say a file, test1 in it:

#!/bin/bash
echo "enter the directory name"
read ab
check(){
if (( echo `mkdir $ab` 2>/dev/null )); then
  echo "directory created "
  echo `ls -ld $ab`
  exit
else
  echo "try again "
  echo "enter new value for directory:"
  read ab
  check
fi
}
check

The problem here is if the directory exists then the program works fine but if it does not exist then it creates it but then goes to the else part of the program.

Best Answer

The echo always succeeds. Do without it and the subshell:

#!/bin/bash
echo "enter the directory name"
read ab
check(){
    if mkdir "$ab" 2>/dev/null; then
      echo "directory created "
      ls -ld "$ab"
      exit
    else
      echo "try again "
      echo "enter new value for directory: "
      read ab
      check
    fi
}
check
Related Question