我正在尝试使用 for 循环来创建在 Arch 安装脚本中选择密码的函数(基于易拱门)使用以下代码(其中使用这重复提示的答案以及这一个用于添加换行符来读取):
#!/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
运行时,我收到以下错误(最后一行被垃圾邮件发送,直到脚本终止):
./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
有谁知道如何解决这个问题?
答案1
简短的回答:不。使用一个函数并向其传递参数。使用关联数组:
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
不是特别说明,但运行它:
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" )