使用 zenity 进行 CIFS 挂载的 Bash 登录脚本

使用 zenity 进行 CIFS 挂载的 Bash 登录脚本

我正在编写一个用于登录后运行的 Windows 共享的挂载脚本。我已经使用 bash 和 zenity 完成了它并且它工作正常,但现在我需要改进它,以便如果用户名字段和密码字段为空则返回输入。

例子

    wUsername=`zenity --entry --width=300 --title="Mount $MOUNTDIR" --text="Kasutajanimi:"`
#if [ $? -ne 0 ]; then
#       exit 1
#fi
if [ -z "$wUsername" ]; then
        zenity --error --title="Viga kasutajanimes!" --text="Palun sisestage oma kasutajanimi"


# get the windows password
wPassword=`zenity --entry --width=300 --title="Mount $MOUNTDIR" --text="Parool:" --hide-text`
if [ $? -ne 0 ]; then
        exit 1
fi

所以我希望这个脚本在以下情况下让用户重新输入卡苏塔贾尼米又名用户名或帕罗尔也就是说密码为空。即使按下空格键。

我已经在万能的 Google 上搜索了它,并且我知道我可以以某种方式使用 return 来实现它。

答案1

我会这样做:

#!/usr/bin/env bash

## Define a function that launches the zenity username dialog
get_username(){
    zenity --entry --width=300 --title="Mount $MOUNTDIR" --text="Kasutajanimi:" 
}
## Define a function that launches the zenity password dialog
get_password(){
    zenity --entry --width=300 --title="Mount $MOUNTDIR" --text="Parool:" --hide-text
}

## Attempt to get the username and exit if cancel was pressed.
wUsername=$(get_username) || exit

## If the username is empty or matches only whitespace.
## See http://www.tldp.org/LDP/abs/html/string-manipulation.html
## for an explanation of this syntax. The . means any non-space
## character so when this is less than 1, the username is empty
## or just whitespace. Since this is a while loop, the process
## will be repeated until the username is correctly submitted.
while [ "$(expr match "$wUsername" '.')" -lt "1" ]; do
    zenity --error --title="Viga kasutajanimes!" --text="Palun sisestage oma kasutajanimi"
    wUsername=$(get_username) || exit
done

## Same as the previous loop but for the password. Sorry if
## the message is wrong, I don't speak this language :)
wPassword=$(get_password) || exit

while [ "$(expr match "$wPassword" '.')" -lt "1" ]; do
    zenity --error --title="Viga Parool!" --text="Palun sisestage oma Parool"
    wPassword=$(get_password) || exit
done

答案2

您可以尝试这样的操作:

# ask for username
while true # start infinity loop
do
    wUsername=`zenity --entry --width=300 --title="Mount $MOUNTDIR" --text="Kasutajanimi:"`

    # user abort
    if [ $? -ne 0 ]; then
          exit 0
    fi

    # remove spaces
    wUsername=$( echo "$wUsername" | tr -d ' ' )

    # check user input
    if [ -z "$wUsername" ]; then
        # user input is empty -> throw error and continue the loop
        zenity --error --title="Viga kasutajanimes!" --text="Palun sisestage oma kasutajanimi"  
    else # user input is not empty 
        break # leave loop
    fi
done

密码输入也一样。

相关内容