如果输出有字符,我需要运行bash命令,如果输出为空,我需要运行其他命令

时间:2014-05-22 06:22:56

标签: python linux bash scripting

我有一个mount脚本,当Python命令输出中包含字符时,我需要运行一个命令,如果输出为空,则运行其他东西。

示例:

## define a function that launched the zenity username dialog
get_username(){
    zenity --entry --width=300 --title="Mount $MOUNTDIR" --text="Username:"
}
# define a function that launched the zenity password dialog
get_password(){
    zenity --entry --width=300 --title="Mount $MOUNTDIR" --text="Password:" --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.
while [ "$(expr match "$wUsername" '.')" -lt "1" ]; do
    zenity --error --title="Error in username!" --text="Please check your username! Username field can not be empty!"  || exit
    wUsername=$(get_username) || exit
done

wPassword=$(get_password) || exit

while [ "$(expr match "$wPassword" '.')" -lt "1" ]; do
    zenity --error --title="Error in password!" --text="Please check your password! Password field can not be empty!" || exit
    wPassword=$(get_password) || exit
done

Save_pwd=$(python -c "import keyring; keyring.set_password('My namespace', 'wUsername', '$wPassword')")

Get_wPassword=$(python -c "import keyring; keyring.get_password('My namespace', '$wUsername')")

echo $Get_wPassword
# mount windows share to mountpoint
#sudo mount -t cifs //$SERVER/$SHARE ${HOME}/${DIRNAME} -o username=${wUsername},password=${Get_wPassword},domain=${DOMAIN}

# show if mounting was OK or failed
#if [ $? -eq 0 ]; then
#       zenity --info --title="Mounting public share succeeded!" --text="Location Documents/Shares/public!"
#else
#       zenity --error --title="Mounting public did not succed!" --text="Please contact system administrator!"
#fi

现在在这个脚本中我需要先运行zenity用户名输入。一旦运行,Python $ Get_wPassword 将运行,一旦它提供非空的输出,它将运行mount命令,其用户名和密码来自 $ Get_wPassword 即可。如果 $ Get_wPassword 为空,那么我需要使用 $ Save_pwd mount命令运行密码输入,以便将密码保存到密钥环中脚本运行的时间从那里获取密码。

我怎样才能做到这一点?使用 while 循环?如果是的话,你能举一些例子吗?我是脚本新手。

1 个答案:

答案 0 :(得分:1)

据我了解,如果名为Get_wPassword的shell变量为非空,则需要一些命令,如果为空,则需要另一个命令。幸运的是,对于空字符串有一个简单的shell测试:

if [ -n "$Get_wPassword" ]
then
    CommandIfNotEmpty
else
    CommandIfEmpty
fi

如果[ -n somestring ]具有非零长度,则构造somestring返回true,如果字符串为空,则返回false。有关详细信息,请参阅man bash

猜测你真正想做的事情,考虑一下:

if [ -n "$Get_wPassword" ]
then
    if sudo mount -t cifs //$SERVER/$SHARE ${HOME}/${DIRNAME} -o username=${wUsername},password=${Get_wPassword},domain=${DOMAIN}
    then
        zenity --info --title="Mounting public share succeeded!" --text="Location Documents/Shares/public!"
    else
        zenity --error --title="Mounting public did not succed!" --text="Please contact system administrator!"
    fi
else
    echo "Password was empty..."
fi