variable undefined after nested for loop

136 Views Asked by At

I'm trying to create a script that allows a user to choose backup destinations from the mounted volumes.

While I had a first draft working it had repetition which I've tried to remove by rebuilding in a nested for loop, however by the end of the script my variables become undefined and i can't see what mistake I've made.

why are my variables defined at line 19 but not at lines 27-29?

I am a beginner, apologies if the answer is obvious.

#!/bin/bash

VOLUMES=$(ls /volumes)

WORKING_DRIVE=
MASTER_DRIVE=
CLONE_DRIVE=

echo
for BACKUP_DESTINATION in 'Working Drive' 'Master Drive' 'Clone Drive'
do
    for VOLUME_VARIABLE in "${WORKING_DRIVE}" "${MASTER_DRIVE}" "${CLONE_DRIVE}"
    do
        echo "Select your ${BACKUP_DESTINATION}"
        echo
        select VOLUME_VARIABLE in $VOLUMES
        do
            echo
            echo "${BACKUP_DESTINATION}: $VOLUME_VARIABLE"
            echo
            break
        done
        break
    done
done

echo "Working Drive is: ${WORKING_DRIVE}"
echo "Master Drive is: ${MASTER_DRIVE}"
echo "Clone Drive is: ${CLONE_DRIVE}"
1

There are 1 best solutions below

3
On

You can do something like this:

#!/bin/bash

VOLUMES=$(ls /volumes)
DATA=''

function selectDestination() {
    echo "Select your ${1}"
    echo
    select VOLUME_VARIABLE in $VOLUMES
    do
        echo
        echo "${1}: $VOLUME_VARIABLE"
        echo
        break
    done

    DATA=${VOLUME_VARIABLE}
}

echo

selectDestination 'Working Drive'
WORKING_DRIVE=${DATA}
selectDestination 'Master Drive'
MASTER_DRIVE=${DATA}
selectDestination 'Clone Drive'
CLONE_DRIVE=${DATA}


echo "Working Drive is: ${WORKING_DRIVE}"
echo "Master Drive is: ${MASTER_DRIVE}"
echo "Clone Drive is: ${CLONE_DRIVE}"