4

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
user1852516
  • 41
  • 1
  • 1
  • 2
  • After looking at what you guys said, I just changed the name of my function. Tanks for the help. – user1852516 Dec 08 '12 at 01:12
  • You can always run gdb on the core dump to find out exactly where the program is crashing...in this case, happily, gdb is not needed. – Charles Boyd Dec 08 '12 at 01:20

2 Answers2

4

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.

ormaaj
  • 6,201
  • 29
  • 34
2

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.