How can I run a function from a script in command line?

Well, while the other answers are right – you can certainly do something else: if you have access to the bash script, you can modify it, and simply place at the end the special parameter "$@" – which will expand to the arguments of the command line you specify, and since it’s “alone” the shell will try to call them verbatim; and here you could specify the function name as the first argument. Example:

$ cat test.sh
testA() {
  echo "TEST A $1";
}

testB() {
  echo "TEST B $2";
}

"$@"


$ bash test.sh
$ bash test.sh testA
TEST A 
$ bash test.sh testA arg1 arg2
TEST A arg1
$ bash test.sh testB arg1 arg2
TEST B arg2

For polish, you can first verify that the command exists and is a function:

# Check if the function exists (bash specific)
if declare -f "$1" > /dev/null
then
  # call arguments verbatim
  "$@"
else
  # Show a helpful error
  echo "'$1' is not a known function name" >&2
  exit 1
fi

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)