如果输出有字符则运行一个bash命令,输出为空则运行另一个命令

0 投票
1 回答
507 浏览
提问于 2025-04-18 07:16

我有一个挂载脚本,我需要在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会执行,然后如果它的输出不为空,就会用从$Get_wPassword得到的用户名和密码来运行mount命令。如果$Get_wPassword是空的,那我就需要用$Save_pwd来运行密码输入和mount命令,这样就能把密码保存到钥匙串里,下次脚本运行的时候就能从那里取出密码。

我该怎么做呢?用while循环可以吗?如果可以的话,能给我一些例子吗?我刚开始接触脚本编写。

1 个回答

1

我理解你想要做的是,如果一个叫做 Get_wPassword 的变量不为空,就执行一个命令;如果它为空,就执行另一个命令。幸运的是,Shell中有一个简单的方法可以检查字符串是否为空:

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

这个写法 [ -n somestring ] 会返回真(true),如果 somestring 这个字符串的长度大于零;如果字符串是空的,它就会返回假(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

撰写回答