记得bash变量再次运行脚本

时间:2013-12-01 22:14:38

标签: bash shell variables scripting boolean

我正在尝试测试一个帐户是否被锁定,使用值“1”来设置锁定,如果不允许用户登录。(这只是一个学习bash的愚蠢脚本,不是真正的登录,所以忽略任何安全漏洞!)

尝试失败3次后,应将标志设置为1,然后退出脚本。但是,当第二次运行脚本时,它再次将其设置为默认值0,而不是由于该标志而无法运行。

我怀疑问题是由于我将flag变量默认为0以避免有关未初始化变量的错误,但我不知道如何让它“记住”变量被设置为1为每个实例的脚本运行。

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

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

我通过使用名为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

答案 1 :(得分:0)

从终端启动脚本使脚本从终端继承环境变量。该脚本中设置的任何环境变量仅在同一脚本的执行时间内有效。一旦退出,就会离开环境变量。

您必须使用其他内容(例如文件)来跟踪多个脚本执行期间的更改。