user1852516
user1852516

Reputation: 41

Segmentation fault (core dumped) error in unix shell script. Help finding bug?

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

Upvotes: 4

Views: 14010

Answers (2)

ormaaj
ormaaj

Reputation: 6577

The date function is calling itself recursively with no termination condition. This will probably always segfault in Bash. Use command date to call the date command instead of the function. In bash 4.2 you can also set a recursion depth limit by setting the FUNCNEST variable to help detect such errors.

Upvotes: 4

user149341
user149341

Reputation:

Your date function 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.

Upvotes: 2

Related Questions