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

LinuxBashScripting

Linux Problem Overview


I have a script that has some functions.

Can I run one of the function directly from command line?

Something like this?

myScript.sh func()

Linux Solutions


Solution 1 - Linux

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

Solution 2 - Linux

If the script only defines the functions and does nothing else, you can first execute the script within the context of the current shell using the source or . command and then simply call the function. See help source for more information.

Solution 3 - Linux

The following command first registers the function in the context, then calls it:

. ./myScript.sh && function_name

Solution 4 - Linux

Briefly, no.

You can import all of the functions in the script into your environment with source (help source for details), which will then allow you to call them. This also has the effect of executing the script, so take care.

There is no way to call a function from a shell script as if it were a shared library.

Solution 5 - Linux

Using case

#!/bin/bash

fun1 () {
    echo "run function1"
    [[ "$@" ]] && echo "options: $@"
}

fun2 () {
    echo "run function2"
    [[ "$@" ]] && echo "options: $@"
}

case $1 in
    fun1) "$@"; exit;;
    fun2) "$@"; exit;;
esac

fun1
fun2

This script will run functions fun1 and fun2 but if you start it with option fun1 or fun2 it'll only run given function with args(if provided) and exit. Usage

$ ./test 
run function1
run function2

$ ./test fun2 a b c
run function2
options: a b c

Solution 6 - Linux

I have a situation where I need a function from bash script which must not be executed before (e.g. by source) and the problem with @$ is that myScript.sh is then run twice, it seems... So I've come up with the idea to get the function out with sed:

sed -n "/^func ()/,/^}/p" myScript.sh

And to execute it at the time I need it, I put it in a file and use source:

sed -n "/^func ()/,/^}/p" myScript.sh > func.sh; source func.sh; rm func.sh

Solution 7 - Linux

Edit: WARNING - seems this doesn't work in all cases, but works well on many public scripts.

If you have a bash script called "control" and inside it you have a function called "build":

function build() { 
  ... 
}

Then you can call it like this (from the directory where it is):

./control build

If it's inside another folder, that would make it:

another_folder/control build

If your file is called "control.sh", that would accordingly make the function callable like this:

./control.sh build

Solution 8 - Linux

Solved post but I'd like to mention my preferred solution. Namely, define a generic one-liner script eval_func.sh:

#!/bin/bash
source $1 && shift && "@a"

Then call any function within any script via:

./eval_func.sh <any script> <any function> <any args>...

An issue I ran into with the accepted solution is that when sourcing my function-containing script within another script, the arguments of the latter would be evaluated by the former, causing an error.

Solution 9 - Linux

The other answers here are nice, and much appreciated, but often I don't want to source the script in the session (which reads and executes the file in your current shell) or modify it directly.

I find it more convenient to write a one or two line 'bootstrap' file and run that. Makes testing the main script easier, doesn't have side effects on your shell session, and as a bonus you can load things that simulate other environments for testing. Example...

# breakfast.sh
make_donuts() { 
     echo 'donuts!'
}

make_bagels() {
     echo 'bagels!'
}
# bootstrap.sh
source 'breakfast.sh'

make_donuts

Now just run ./bootstrap.sh.Same idea works with your python, ruby, or whatever scripts.

Why useful? Let's say you complicated your life for some reason, and your script may find itself in different environments with different states present. For example, either your terminal session, or a cloud provider's cool new thing. You also want to test cloud things in terminal, using simple methods. No worries, your bootstrap can load elementary state for you.

# breakfast.sh
# Now it has to do slightly different things
# depending on where the script lives!

make_donuts() {
    if [[ $AWS_ENV_VAR ]]
    then
        echo '/donuts'
    elif [[ $AZURE_ENV_VAR ]]
    then
        echo '\donuts'
    else 
        echo '/keto_diet'
    fi
}

If you let your bootstrap thing take an argument, you can load different state for your function to chew, still with one line in the shell session:

# bootstrap.sh
source 'breakfast.sh'

case $1 in
    AWS)
        AWS_ENV_VAR="arn::mumbo:jumbo:12345"
    ;;
    AZURE)
        AZURE_ENV_VAR="cloud::woo:_impress"
    ;;
esac

make_donuts # You could use $2 here to name the function you wanna, but careful if evaluating directly.

In terminal session you're just entering: ./bootstrap.sh AWS Result: # /donuts

Solution 10 - Linux

you can call function from command line argument like below

function irfan() {
echo "Irfan khan"
date
hostname
}
function config() {
ifconfig
echo "hey"
}
$1

Once you defined the functions put $1 at the end to accept argument which function you want to call. Lets say the above code is saved in fun.sh. Now you can call the functions like ./fun.sh irfan & ./fun.sh config in command line.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAAaaView Question on Stackoverflow
Solution 1 - LinuxsdaauView Answer on Stackoverflow
Solution 2 - LinuxSven MarnachView Answer on Stackoverflow
Solution 3 - LinuxTimonWangView Answer on Stackoverflow
Solution 4 - LinuxsorpigalView Answer on Stackoverflow
Solution 5 - LinuxIvanView Answer on Stackoverflow
Solution 6 - LinuxChristoph LöschView Answer on Stackoverflow
Solution 7 - LinuxArturas MView Answer on Stackoverflow
Solution 8 - LinuxEvanView Answer on Stackoverflow
Solution 9 - LinuxRabView Answer on Stackoverflow
Solution 10 - LinuxIrfan KhanView Answer on Stackoverflow