1

This question already has an answer here:

I am trying to output success when number of positional parameters is equal to 1, error otherwise.

#!/usr/bin/env bash

foo() {
  if [[ "$#" -ne 1 ]]
  then echo "error"
  else
    echo "success"
  fi
}
foo

I execute the script with command ./my_script 1. The output is always error no matter if I run the script with command ./my_script 1 or ./my_script 1 2.

I expect ./my_script 1 to output success.

marked as duplicate by Jesse_b, Kusalananda bash Dec 7 '18 at 18:00

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • I cannot reproduce your results, are you sure you don't have a typo somewhere? If you add echo "$#" to a line before your test construct, can you confirm it's recognizing the correct number of arguments? – Jesse_b Dec 7 '18 at 17:41
  • I think I do have a typo – HarshvardhanSharma Dec 7 '18 at 17:42
  • I reproduced the exact situation. Yes, echo "$#" is recognising the correct number of arguments. – HarshvardhanSharma Dec 7 '18 at 17:50
2

Thank you for posting a new question! Seeing the code in use clarifies the situation.

You've passed along one argument to the overall script, but no arguments to the foo function!

If you want the script's arguments inside the function, pass them along:

foo() {
  if [[ "$#" -ne 1 ]]
  then echo "error"
  else
    echo "success"
  fi
}
foo "$@"

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