Bash中显示返回值的非常基本的函数
我对Bash有一些问题,我已经习惯了现代语言,我需要在Bash中开发一些东西,但有些东西不能像我所希望的那样工作 我有一个功能:Bash中显示返回值的非常基本的函数,bash,cgi,Bash,Cgi,我对Bash有一些问题,我已经习惯了现代语言,我需要在Bash中开发一些东西,但有些东西不能像我所希望的那样工作 我有一个功能: function is_directory { if (test -d "$1"); then return true fi return false } 我调用此函数,但我想在网页上回显结果,(我正在使用CGI)。。那么如何回显返回的值呢 echo is_directory "/home/pepe" 不会显示true它将“is_directory”/
function is_directory
{
if (test -d "$1"); then
return true
fi
return false
}
我调用此函数,但我想在网页上回显结果,(我正在使用CGI)。。那么如何回显返回的值呢
echo is_directory "/home/pepe"
不会显示true它将“is_directory”/home/pepe”显示为字符串本身u.u
如何显示字符串返回值
谢谢 最好的方法是
echo
在函数本身中输出您想要的答案,如下所示:
is_directory()
{
[[ -d "$1" ]] && echo true || echo false
}
输出
Bash和其他shell以int形式返回范围为0-255的退出代码。使用
return true
或return false
总是会产生错误,因为return
需要一个数值。您可以访问特殊变量$?
中的返回值
$ foo () { return 42; }; foo; echo $?
42
以下是编写函数的一些方法:
返回一个值:
is_directory () {
test -d "$1"
}
要使用它:
if is_directory "foo" # note that there are no parentheses or brackets
then
echo "true"
else
echo "false"
fi
if [[ $(is_directory "foo") == true ]]
then
do_something
fi
输出一个字符串:
is_directory () {
if [ -d "$1" ]
then
echo "true"
else
echo "false"
fi
}
要使用它:
if is_directory "foo" # note that there are no parentheses or brackets
then
echo "true"
else
echo "false"
fi
if [[ $(is_directory "foo") == true ]]
then
do_something
fi
使用此函数的最新版本,您可以执行问题中显示的命令,如下所示:
echo "$(is_directory "/home/pepe")"
它将输出“真”或“假”,但不需要回声。这将做同样的事情:
is_directory "/home/pepe"
尝试echois_目录”//home/page“
这是echo is_目录”//home/page”