1

I'm trying to create directory using if condition statement, while running script i am not able to find any expected result from the script, but when i am running manually only mkdir command alone its creating as we expected; here the sample code.

#!/bin/bash

dir_path=/tmp/opt/app/software/{A,B,C,D}

if [[ -d  $dir_path ]]; then
            mkdir -p /tmp/opt/app/software/{A,B,C,D}
fi

can you please advise, how we can create this..

1 Answer 1

5

dir_path is a "list" of directory paths due to the {} parameter expansion. If you write this out:

dir_path=/tmp/opt/app/software/A /tmp/opt/app/software/B /tmp/opt/app/software/C /tmp/opt/app/software/D

This is what's being used in the test of the if statement.

Either you want to iterate over the list of sub directories, or just pass them to mkdir. mkdir simply won't create the directory if it already exists.

Your mkdir command actually expands out to:

mkdir -p /tmp/opt/app/software/A /tmp/opt/app/software/B /tmp/opt/app/software/C /tmp/opt/app/software/D

If you want to itterate and still do a check (which while needless in this example can still be useful other times.)

# Declare the variable `dirs` to be an array and use
# parameter expansion to populate it
declare -a dirs=(/tmp/opt/app/software/{A,B,C,D});

# Iterate over the array of directory names
for dir in ${dirs[@]}; do
    if [ ! -d "$dir" ]; then
        # The directory does not exsist
        mkdir -p "$dir";  # Make the directory
    fi
done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.