学习 bash 内建命令 true 的用法
时间:2014-09-10 21:27 来源:linux.it.net.cn 作者:it
true 是 bash 的内建命令,它的返回值($? 的值)是 0(代表执行成功)。和 true 相对应的命令是 false 命令,它也是 bash 的内建命令,它的返回值是 1(代表执行失败)。
true 和 false 这两个命令常用于在 script 中作为空命令来执行;或者表示一个总是返回真值、或者假值的条件表达式;或者用于设置函数的返回状态。
例1,test.sh:
复制代码代码如下:
true
echo \$?=$?
false
echo \$?=$?
! true
echo \$?=$?
! false
echo \$?=$?
在命令提示符
下输入 ./test.sh,执行结果如下:
$?=0
$?=1
$?=1
$?=0
例2,test.sh:
复制代码代码如下:
#!/bin/bash
# infinite loop
while true
do
echo -n "please input account : "; read user
if [ $user == "user" ]
then
echo "correct account"
break
else
echo "wrong account"
fi
done
在命令提示符下输入 ./test.sh,执行结果如下:
please input account : root
wrong account
please input account : user
correct account
例3,test.sh:
复制代码代码如下:
#!/bin/bash
account ()
{
if [ $1 == "user" ]
then
true
else
false
fi
}
# infinite loop
while true
do
echo -n "please input account : "; read user
account $user; ret=$?
if [ $ret -eq 0 ]
then
echo "correct account"
break
else
echo "wrong account"
fi
done
在命令提示符下输入 ./test.sh,执行结果如下:
please input account : root
wrong account
please input account : user
correct account
(责任编辑:IT)
true 是 bash 的内建命令,它的返回值($? 的值)是 0(代表执行成功)。和 true 相对应的命令是 false 命令,它也是 bash 的内建命令,它的返回值是 1(代表执行失败)。
例1,test.sh:
复制代码代码如下:
true
false
! true
! false 在命令提示符
下输入 ./test.sh,执行结果如下:
例2,test.sh:
复制代码代码如下:
#!/bin/bash
# infinite loop while true do echo -n "please input account : "; read user if [ $user == "user" ] then echo "correct account" break else echo "wrong account" fi done
在命令提示符下输入 ./test.sh,执行结果如下:
例3,test.sh:
复制代码代码如下:
#!/bin/bash
# infinite loop
在命令提示符下输入 ./test.sh,执行结果如下: |