How to call a function in shell Scripting?

后端 未结 7 1038
情话喂你
情话喂你 2020-12-05 05:06

I have a shell script which conditionally calls a function.

For Example:-

if [ \"$choice\" = \"true\" ]
then 
  process_install
elif [ \"$choice\" =          


        
7条回答
  •  無奈伤痛
    2020-12-05 05:50

    You don't specify which shell (there are many), so I am assuming Bourne Shell, that is I think your script starts with:

    #!/bin/sh
    

    Please remember to tag future questions with the shell type, as this will help the community answer your question.

    You need to define your functions before you call them. Using ():

    process_install()
    {
        echo "Performing process_install() commands, using arguments [${*}]..."
    }
    
    process_exit()
    {
        echo "Performing process_exit() commands, using arguments [${*}]..."
    }
    

    Then you can call your functions, just as if you were calling any command:

    if [ "$choice" = "true" ]
    then
        process_install foo bar
    elif [ "$choice" = "false" ]
    then
        process_exit baz qux
    

    You may also wish to check for invalid choices at this juncture...

    else
        echo "Invalid choice [${choice}]..."
    fi
    

    See it run with three different values of ${choice}.

    Good luck!

提交回复
热议问题