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 ?

  • Do you have set -e in your script? – Stephen Kitt Nov 3 '16 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. – Konstantin Morenko Nov 3 '16 at 18:00
  • Please mark answer if it solves your problem or comment you troubles. Thank you. – Konstantin Morenko Nov 3 '16 at 18:12
  • @StephenKitt It works when I comment set -o errexit set -o errtrace – Chuck Noxis Nov 3 '16 at 18:14
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.

  • 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 ] ? – Chuck Noxis Nov 3 '16 at 18:19
  • Inside the test [ and ] the = operator works like == and tests the string equality (not numbers). – Konstantin Morenko Nov 3 '16 at 19:37
  • OKKKKKK Thanks a lot, i didn't knew that ! It's always a pleasure to learn from Stack ! :) – Chuck Noxis Nov 4 '16 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.