记住bash变量以再次运行脚本
我试图测试帐户是否被锁定,使用值“1”设置锁定,如果不允许用户登录。(这只是一个学习bash的愚蠢脚本,不是真正的登录,所以忽略任何安全缺陷!) 尝试3次失败后,应将标志设置为1,然后退出脚本。但是,当第二次运行脚本时,它会再次将其设置为默认值0,而不是由于该标志而无法运行 我怀疑问题是由于我将标志变量默认为0,以避免未初始化变量的错误,但我不知道如何“记住”脚本运行的每个实例的变量都设置为1记住bash变量以再次运行脚本,bash,shell,variables,scripting,boolean,Bash,Shell,Variables,Scripting,Boolean,我试图测试帐户是否被锁定,使用值“1”设置锁定,如果不允许用户登录。(这只是一个学习bash的愚蠢脚本,不是真正的登录,所以忽略任何安全缺陷!) 尝试3次失败后,应将标志设置为1,然后退出脚本。但是,当第二次运行脚本时,它会再次将其设置为默认值0,而不是由于该标志而无法运行 我怀疑问题是由于我将标志变量默认为0,以避免未初始化变量的错误,但我不知道如何“记住”脚本运行的每个实例的变量都设置为1 let x=0 let attempts=0 let PinCode=1234 #checks if
let x=0
let attempts=0
let PinCode=1234
#checks if locked, default variable value set to 0 (so it is initiated even if first time running script)
if [ ${locked:-0} -eq 1 ]
then
echo "You are locked out of your account."
else
#runs if unlocked, until third attempt or successful entry
until [ $attempts -eq 3 -o $PinCode -eq $x ]
do
echo "Enter your PIN number"
read x
if [ $x -eq $PinCode ]
then
echo "Welcome $USER you have correctly entered your PIN. You are connecting from $SSH_CLIENT at $HOSTNAME."
else
let attempts=attempts+1
echo -e "Incorrect PIN number"
echo -e "\nYou have entered your pin number incorrectly $attempts times. At 3 failures you will be locked out of your
account!"
#locks account on third attempt
if [ $attempts -eq 3 ]
then let locked=1
fi
fi
done
fi
exit 0
非常感谢您的帮助 从终端启动脚本会使脚本从终端继承环境变量。该脚本中设置的任何环境变量仅在同一脚本的执行期间有效。一旦退出,环境变量就会消失
您必须使用其他东西,例如文件,来跟踪脚本多次执行期间的更改。我使用名为account.locked的文件作为我的标志,使用“touch”创建它,并使用if[-f filename]检查它是否存在,从而修复了它
let x=0
let attempts=0
let PinCode=1234
#checks if locked by searching for flag file
if [ -f locked.account ]
then
echo "You are locked out of your account."
else
#runs if unlocked, until third attempt or successful entry
until [ $attempts -eq 3 -o $PinCode -eq $x ]
do
echo "Enter your PIN number"
read x
if [ $x -eq $PinCode ]
then
echo "Welcome $USER you have correctly entered your PIN. You are connecting from $SSH_CLIENT at $HOSTNAME."
else
let attempts=attempts+1
echo -e "Incorrect PIN number"
echo -e "\nYou have entered your pin number incorrectly $attempts times. At 3 failures you will be locked out of your
account!"
#locks account on third attempt by creating a flag file as a type of global variable replacement
if [ $attempts -eq 3 ]
then touch locked.account
echo "You are locked out of your account."
fi
fi
done
fi
exit 0