Linux Bash 脚本函数返回值问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4538145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script function return value problem
提问by Eedoh
Can anyone help me return the correct value from a bash script function?
谁能帮我从 bash 脚本函数返回正确的值?
Here's my function that should return first (and only) line of the file passed as an argument:
这是我的函数,它应该返回作为参数传递的文件的第一行(也是唯一行):
LOG_FILE_CREATION_TIME()
{
return_value=`awk 'NR==1' `
return return_value
}
And here's my call of that function in the other script:
这是我在另一个脚本中对该函数的调用:
LOG_FILE_CREATION_TIME "logfile"
timestamp=$?
echo "Timestamp = $timestamp"
I always get some random values with this code. If, for example, there's a value of 62772031 in the "logfile", I get
我总是用这段代码得到一些随机值。例如,如果“日志文件”中有一个值为 62772031,我得到
Timestamp = 255
时间戳 = 255
as an output. For some other values in the file, I get other random values as a return value, never the correct one.
作为输出。对于文件中的其他一些值,我得到其他随机值作为返回值,从来没有正确的值。
Any ideas?
有任何想法吗?
采纳答案by plundra
The exit code is limited to 0 - 255
, you cannot use it for a timestamp.
退出代码仅限于0 - 255
,您不能将其用于时间戳。
Echo your timestamp instead, since you don't seem to be outputing anything else; this ought to be fine?
改为回显您的时间戳,因为您似乎没有输出任何其他内容;这应该没问题吧?
LOG_FILE_CREATION_TIME()
{
# If you want to do some more stuff, you might want
# to use the intermediate variable as you first did.
awk 'NR==1'
}
timestamp=$(LOG_FILE_CREATION_TIME "logfile")
echo "Timestamp = $timestamp"
You might have simplified the function in your example, because if all you wanted was the first line, why not use head -1 logfile
instead?
您可能已经简化了示例中的函数,因为如果您想要的只是第一行,为什么不head -1 logfile
改用呢?
回答by Keith
Shell functions work like commands. They can only return errorlevel values (integers). To get strings you can either set a global variable, or print/echo the value and then have the caller use the command substitution (like back-ticks).
Shell 函数像命令一样工作。它们只能返回错误级别值(整数)。要获取字符串,您可以设置全局变量,或打印/回显该值,然后让调用者使用命令替换(如反引号)。
This works:
这有效:
#!/bin/bash
LOG_FILE_CREATION_TIME()
{
return_value=`awk 'NR==1' `
echo $return_value
}
timestamp=$(LOG_FILE_CREATION_TIME )
echo $timestamp
Unrelated, but BTW in Python:
不相关,但在 Python 中顺便说一句:
#!/usr/bin/python2
import sys
print open(sys.argv[1]).readline()
;-)
;-)
回答by Αλ?κο?
Another way is to use a global variable. You can have multiple "return" variables this way. It does not actually return anything, but does the trick.
另一种方法是使用全局变量。您可以通过这种方式拥有多个“返回”变量。它实际上并没有返回任何东西,但是可以解决问题。
#!/bin/sh
concat_ret
concat() {
for s in $*
do
concat_ret="$concat_ret $s"
done
return 0
}
echo "starting"
concat String1 String2 String3 "and many other strings"
echo $?
echo $concat_ret
exit 0
Output
输出
starting
0
String1 String2 String3 and many other strings