0

I'm trying to use a for loop to create functions for choosing passwords in my Arch install script (based on easy-arch) using the following code (which uses this se answer for repeating prompts and this one for adding newlines to read):

#!/bin/bash
errEcho() { echo -e "${BOLD}${BRED}[ ${BBLUE}•${BRED} ] $1${RESET}"; }
for type in encrypt user root; do
    pick_${type}pass() {
            read -rsp "Enter $type password: " ${type}pass
            read -rsp $'\nVerify password: ' ${type}pass2
            echo
            if [ "$typepass" != "$typepass2" ]; then
                errEcho "Passwords don't match."
                return 1
            fi
            return 0
    }
done
until pick_userpass; do : ; done

When this is run I get the following errors (last line is spammed until script gets terminated):

./looptest.sh: line 3: `pick_${type}pass': not a valid identifier
./looptest.sh: line 3: `pick_${type}pass': not a valid identifier
./looptest.sh: line 3: `pick_${type}pass': not a valid identifier
./looptest.sh: line 15: pick_userpass: command not found

Does anyone know how a solution to this?

1 Answers1

1

Short answer: don't. Use one function and pass parameters to it. Using an associative array:

pick_pass() {
    local type=$1
    local pass pass2
    while true; do
        read -rsp "Enter $type password: " pass
        read -rsp $'\nVerify password: ' pass2
        echo
        [[ "$pass" == "$pass2" ]] && break
        errEcho "Passwords don't match."
    done
    password[$type]=$pass
}

declare -A password

for type in encrypt user root; do pick_pass $type done

declare -p password

Not particularly illustrative, but running it:

declare -p password
Enter encrypt password:
Verify password:
Enter user password:
Verify password:
Enter root password:
Verify password:
bash: errEcho: command not found
Enter root password:
Verify password:
declare -A password=([encrypt]="foo" [root]="asdf" [user]="bar" )
glenn jackman
  • 85,964