1

This is a extract of my code:

ninja ()
{
  if $1 = toto
  then
  return 1
  elif $1 = tata
  then
  return 4
  fi
}

main () {
  ninja "tata"
  if [ $? -ne 1 ]
  then
    somecode
  fi
}

main "$@"

For no reason, when my function return something, the program just exit (I've tested with a trap EXIT), the function return 4 and execute the trap.

Edit : works when I comment

set -o errexit
set -o errtrace

But how Can I found the error ?

4
  • Do you have set -e in your script? Nov 3, 2016 at 17:37
  • There was not conflict, I've found that redefinition allowed and for calling builtin command then you need a builtin <command> construct. Nov 3, 2016 at 18:00
  • Please mark answer if it solves your problem or comment you troubles. Thank you. Nov 3, 2016 at 18:12
  • @StephenKitt It works when I comment set -o errexit set -o errtrace Nov 3, 2016 at 18:14

1 Answer 1

1

If you want to test that function argument equivalent to some string, you must use construct if [ "$x" == "string" ], then your code will looks like:

test () {
  if [ "$1" == "toto" ] then
    return 1
  elif [ "$1" == "tata" ] then
    return 4
  fi
}

main () {
  test "tata"
  if [ $? -ne 1 ] then
    echo "somecode"
  fi
}

main "$@"

And you could use test name for the function. If you want to call builtin test, then use builtin test construct.

And take care about = (assignment) and == (comparison). Inside the test [ and ] the = operator works like == and tests the string equality (not numbers).

set -o errexit exits immediately after command returns non-zero (non-succesful). Your ninja returns 1 (which is non-zero) and exit.

Your code without tests is not working cause if statement tries to execute instructions into it and determine the exit state of the command: if the exit state is zero (success), then execute instructions after then till elif of fi.

3
  • It's not this. I check another thing but it's for the exemple of the structure of my code. I put test in name of function but it's not his true name. Why = works in this case ? if [ toto = 5 ] ? Nov 3, 2016 at 18:19
  • Inside the test [ and ] the = operator works like == and tests the string equality (not numbers). Nov 3, 2016 at 19:37
  • OKKKKKK Thanks a lot, i didn't knew that ! It's always a pleasure to learn from Stack ! :) Nov 4, 2016 at 9:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .