开发者

Very basic function in Bash showing returned value

I have some questions about Bash, im used to modern languages and i need to develop some stuff in Bash but some things doesn't work as i want.

I have a function开发者_JAVA百科 :

function is_directory
{
 if (test -d "$1"); then 
  return true
 fi
 return false
}

i call this function but i want to echo the result on a webpage, (im working with CGI) .. so how do i echo returned values?

echo is_directory "/home/pepe"

wont display true it will display " is_directory "/home/pepe" " as a string itself u.u

and how do i display string returned values ??

Thanks!


Best way to do it is to echo out the answer you want in the function itself like so:

is_directory()
{
  [[ -d "$1" ]] && echo true || echo false
}

Output

$ is_directory /etc
true

$ is_directory /foo
false


Bash and other shells return an exit code as an int in the range 0-255. Using return true or return false always produces an error since return expects a numeric value. You can access the return value in the special variable $?.

$ foo () { return 42; }; foo; echo $?
42

Here are some ways to write your function:

Return a value:

is_directory () {
    test -d "$1"
}

To use it:

if is_directory "foo"    # note that there are no parentheses or brackets
then
    echo "true"
else
    echo "false"
fi

Output a string:

is_directory () {
    if [ -d "$1" ]
    then
        echo "true"
    else
        echo "false"
    fi
}

To use it:

if [[ $(is_directory "foo") == true ]]
then
    do_something
fi

Using this last version of the function, you can do the command that you show in your question like this:

echo "$(is_directory "/home/pepe")"

which will output "true" or "false" but the echo is unnecessary. This will do the same thing:

is_directory "/home/pepe"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜