bash unix shell 脚本中的分段错误(核心转储)错误。帮忙找bug?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13773362/
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
Segmentation fault (core dumped) error in unix shell script. Help finding bug?
提问by user1852516
Now, I already know that this means that there is a bug, But I cant find it. Could you help review my code and try to spot what is wrong? The error message revolves around the date function I created. All the other functions work fine in this code.
现在,我已经知道这意味着存在一个错误,但我找不到它。你能帮忙检查我的代码并尝试找出问题所在吗?错误消息围绕我创建的日期函数。所有其他函数在这段代码中都可以正常工作。
Error:
错误:
sguthrie1@cs:~$ ./finalproject.sh -d
Segmentation fault (core dumped)
Code:
代码:
function check
{
echo "usage: hw14.sh option argument
Please enter one or more options or arguments."
exit
}
function date
{
if [[ $myvar == "-d" ]]
then date "+%d %B,%Y"
fi
}
function host
{
if [[ $myvar == "-h" ]]
then hostname
fi
}
function who
{
if [[ $myvar == "-w" ]]
then whoami
fi
}
function help
{
if [[ $myvar == "-help" ]]
then echo "
valid options:
-d = display today's date in day-month-year format
-h = display name of computer you are currently working on
-w = display who you are logged in as
arguments:
Any argument entered is checked to see if it is a file name
"
fi
}
if [ $# -le 0 ]
then check
fi
for myvar
do
if [[ $myvar == "-"* ]]
then date; host; who; help
fi
done
回答by ormaaj
The datefunction is calling itself recursively with no termination condition. This will probably always segfaultin Bash. Use command dateto call the date command instead of the function. In bash 4.2 you can also set a recursion depth limit by setting the FUNCNESTvariable to help detect such errors.
该date函数在没有终止条件的情况下递归调用自身。这在 Bash 中可能总是段错误。使用command date调用date命令,而不是功能。在 bash 4.2 中,您还可以通过设置FUNCNEST变量来设置递归深度限制,以帮助检测此类错误。
回答by duskwuff -inactive-
Your datefunction is inadvertently calling itself. You can either rename your function to avoid the conflict, or refer to the system command more specifically as /bin/date.
您的date函数无意中调用了自身。您可以重命名函数以避免冲突,也可以将系统命令更具体地称为/bin/date.

