0

I'm trying to put an if statement within an if statement. It seems to work until the last echo command in the script which doesn't print.

For testing I have created a directory with the same name as the $foldername which is input via a prompt. I am inputting this during the execution of the script. During the running of the script I am choosing the option to overwrite the directory, which works fine. However, I am confused as to why after the folder has been replaced, the script doesn't then move onto the last echo statement:

echo "Folder $foldername has now been created"

This is not being printed on screen which suggest the script isn't exiting the if statement section. Any ideas why?

#!/bin/bash
echo "Please input the folder name you would like to create then press ENTER"
read foldername

if [ -d "/home/location/test_directories/$foldername" ]
then
    echo "$foldername already exists"
    sleep 2
    echo
    echo
    echo "Do you want to overwrite this folder and start afresh?"
    read -p "Type Y overwrite the folder, or N to exit the script" -n 1 -r
    echo

    if [[ $REPLY =~ ^[Yy]$ ]]
    then
        echo "You have chosen to overwrite the folder $foldername"

        rm -rf /home/location/test_directories/$foldername; mkdir /home/location/test_directories/$foldername
        sleep 2
    else
        exit
    fi

    exit
else
    mkdir /home/location/test_directories/$foldername
fi

sleep 2
echo "Folder $foldername has now been created"
3
  • Erugh. The convention when writing programs is to indent your blocks of code rather than running it all down the left-hand side. FTFY. Jul 28, 2016 at 10:54
  • 3
    consider your use of exit Jul 28, 2016 at 10:57
  • 1
    @glennjackman far easier to see when the code's indented Jul 28, 2016 at 10:58

1 Answer 1

6

Yes, you may nest if-statements to your heart's content.

The issue with your code is, as pointed out in comments to the question, the two exit statements. Taking a branch that triggers any of these will terminate the script.

As far as I can see, both exit statements are superfluous and may be removed.

You should also make a habit of double-quoting any variable handed to you by the user, for example $foldername. In this case, to be able to handle folder names with spaces.

... or with newlines, tabs or other "field separators" if you've modified IFS, or with *, ?, [ that are special to the shell, and more if you've enabled the extglob option in bash.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .