0

I need to check if a commandline argument matches the one in a bash script, here is my code.

#!/bin/bash

# lets call this script.sh

myFunction() {
if [[ $2 == '--log' ]]; then
    echo "hello world" >> file.log
else
    echo "Unknown argument"
fi
}

myFunction

Sample input:

bash script.sh --log

But doesn't seem to write anything into file.log

badman
  • 319
  • 1
  • 12
  • 1
    I guess you know that `$2` in a function is not the second command-line argument but the second **function** argument? – Renaud Pacalet Sep 23 '21 at 12:29
  • Please [edit] your question and explain in what way it doesn't work. What input do you use, what output/result/behavior do you get and what would you expect. The script defines a function but does not call it. – Bodo Sep 23 '21 at 12:30

1 Answers1

2

You will need to pass the script's arguments to myFunction:

myFunction "$@"

The "$@" means "all the arguments passed to this script."

Hai Vu
  • 37,849
  • 11
  • 66
  • 93