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

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

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

    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 function end put $1 to accept argument let say above code is saved in fun.sh to run function ./fun.sh irfan & ./fun.sh config

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

    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
    
    0 讨论(0)
提交回复
热议问题