shell中逻辑与的两种表示方法

时间:2023-03-09 04:11:42
shell中逻辑与的两种表示方法

bash中表示逻辑与的两种方法:

(1)[ $state == "running" -a $name == "zone1" ]

(2)[[ $state == "running" && $name == "zone1" ]]

ksh中支持第二种。

实例:

#! /bin/bash
read -p "pelease input your name:" name
read -p "pleaase input your password:" passwd if [ $name == "root" -a $passwd == "123" ]; then
echo "登录成功!"
else
echo "登录失败!"
fi if [[ $name == "root" && $passwd == "123" ]]; then
echo "Login pass"
else
echo "Login fail"
fi 输出结果:
pelease input your name:root
pleaase input your password:123
登录成功!
Login pass

在ksh中read -p的使用好像有问题,会出现./learn_shell.save[2]: read: no query process,这样的错误提示。

因此改成下面的形式:

(1)第一种

echo "ThePrompt\c"

read TheSomthing

echo $TheSomething

(2)第二种

read TheSomething?'ThePrompt'

细微区别就是第一种提示语句后会回车,而第二种不会回车。

实例:

#! /usr/bin/ksh
echo "pelease input your name:"
read name read passwd?"pleaase input your password: " if [[ $name == "root" && $passwd == "123" ]]; then
echo "Login pass"
else
echo "Login fail"
fi # ./learn_shell.save
pelease input your name: (这个地方有回车)
root
pleaase input your password: 123
Login pass