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

前端 未结 9 1415
再見小時候
再見小時候 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: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
    

提交回复
热议问题