Romark14
Romark14

Reputation: 15

Shell script nested If/Else statement

I am having a problem with a nested if/else statement in a bash command. The first set of code worked perfectly, but when adding in a read -p section before this something got thrown off.

The code that works:

#!/bin/bash

(
echo p
echo q
) | sudo fdisk $1

if [ ! -d "$2" ]; then
  if [ -f "$2" ]; then
    echo "$2 exists and is not a directory"
    exit 1
  else
    mkdir "$2"
  fi
fi

function mountDisk ()
{
    sudo mount -o loop,offset=$((2048*512)) $1 $2
}

mountDisk $1 $2

So this worked fine, displayed the fdisk info and carried on to create the folder and mount the drive.

When adding an option to continue with mounting after being given the information i got problems.

The altered section of the code is (the -f was taken out as it was deemed unnecessary):

read -p "Mount $1 ?" $3
if [ "$3" = "Yes" ]; then
    if [ ! -d "$2" ]; then
        echo "$2 exists and is not a directory"
        exit 1
    else
        mkdir "$2"
    fi
else
    exit 1
fi

I have tried several different versions on the first if line ([ $3 == "Yes" ] being the first one). But many gave errors, mainly about unary operator expected.

The problem is that it does not give an error now, it just seems to skip to the second else and exit the program, not creating the folder or mounting the drive.

I have spent a lot of time researching this online and have not been able to correct the problem, so any advice would be hugely appreciated.

Upvotes: 0

Views: 4932

Answers (1)

arco444
arco444

Reputation: 22861

Your syntax for scanning in the value in read is incorrect, I would suggest using a different variable name altogether so you can distinguish between what is and isn't a script argument.

Try:

read -p "Mount $1 ? " userprompt
if [ "$userprompt" = "Yes" ]; then
    if [ ! -d "$2" ]; then
        echo "$2 exists and is not a directory"
        exit 1
    else
        mkdir "$2"
    fi
else
    exit 1
fi

Upvotes: 1

Related Questions