【问题标题】:Segmentation fault (core dumped) error in unix shell script. Help finding bug?unix shell 脚本中的分段错误(核心转储)错误。帮忙找bug?
【发布时间】:2012-12-08 09:07:59
【问题描述】:

现在,我已经知道这意味着有一个错误,但我找不到它。您能帮忙检查我的代码并尝试找出问题所在吗? 错误消息围绕我创建的日期函数。此代码中的所有其他功能都可以正常工作。

错误:

sguthrie1@cs:~$ ./finalproject.sh -d 
Segmentation fault (core dumped)

代码:

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

【问题讨论】:

  • 看了你们说的,我只是把我的函数名改了。坦克寻求帮助。
  • 您可以随时在核心转储上运行 gdb 以找出程序崩溃的确切位置……在这种情况下,很高兴不需要 gdb。

标签: linux bash shell unix review


【解决方案1】:

date 函数在没有终止条件的情况下递归调用自身。这将在 Bash 中 probably always segfault。使用command date 调用日期命令而不是函数。在 bash 4.2 中,您还可以通过设置 FUNCNEST 变量来设置递归深度限制,以帮助检测此类错误。

【讨论】:

    【解决方案2】:

    您的date 函数无意中调用了自己。您可以重命名您的函数以避免冲突,或者更具体地将系统命令称为/bin/date

    【讨论】:

    • 或者调用command date而不是date,让shell使用PATH中的命令。
    猜你喜欢
    • 1970-01-01
    • 2014-08-04
    • 2012-11-19
    • 1970-01-01
    • 2015-03-18
    • 2015-06-25
    • 2021-06-03
    相关资源
    最近更新 更多