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

前端 未结 9 1382
再見小時候
再見小時候 2020-12-07 08:05

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()


        
相关标签:
9条回答
  • 2020-12-07 08:20

    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.

    0 讨论(0)
  • 2020-12-07 08:21

    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.

    0 讨论(0)
  • 2020-12-07 08:29

    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.

    0 讨论(0)
  • 2020-12-07 08:32

    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

    0 讨论(0)
  • 2020-12-07 08:33

    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
    
    0 讨论(0)
  • 2020-12-07 08:34

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

    . ./myScript.sh && function_name
    
    0 讨论(0)
提交回复
热议问题