我已经使用“return”从 shell 函数返回数字,我也知道“echo”用于从函数返回字符串。
1. shell函数返回数字
function test1()
{
#some handling
return 0
}
2. shell函数返回字符串
function test2()
{
# some handling
echo "$data"
}
我有一个情况,我需要从 shell 函数返回数字和字符串。
3.从shell函数返回数字和字符串
dummy algorithm
function validate()
{
var=$2
if var==something
return 1
else
# get modified varible
modifiedvar=call(var)
return 0 modifiedvar
}
validate "string"
最好的方法是什么?
答案1
您可以使用命令替换捕获字符串,并捕获带有返回状态的“数字”:
f() {
echo "Don't panic"
return 42
}
result=$(f)
status=$?
echo "The function returned >$result< and $status"
The function returned >Don't panic< and 42
请记住,返回状态是 0 到 255 之间的数字:
$ f() { echo "$1"; return $2; }
$ result=$(f "big number" 300); status=$?
# ........................^^^
$ echo "The function returned '$result' and $status"
The function returned 'big number' and 44
# .....................................^^
$ result=$(f "small number" -300); status=$?
# ..........................^^^^
$ echo "The function returned '$result' and $status"
The function returned 'small number' and 212
# .......................................^^^
答案2
您正在寻找这样的东西吗?
脚本:
#!/bin/bash
var="$1"
function f() {
if [[ -z "$var" || "$var" = "error" ]]; then
return 1
else
var="bar"
return 0
fi
}
if f; then
echo "function returned $?"
echo "$var OK"
else
echo "function returned $?"
echo "error"
fi
$ ./script
function returned 1
error
$ ./script "error"
function returned 1
error
$ ./script "foo"
function returned 0
bar OK