LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   skip execution of a function in a script. (https://www.linuxquestions.org/questions/programming-9/skip-execution-of-a-function-in-a-script-868750/)

nesrin 03-15-2011 12:36 PM

skip execution of a function in a script.
 
Hello,

I have a bash script which is composed of different functions. I want to able to
select which functions to be executed when i run the script, for that i thought about using a flag in the function. but i dont know how to skip the function whose flag is set to zero. any idea? or any other way to do this?
I would appreciate much any help :)

Code:

myfunc1(){
local flag=1
commands
{
func

myfunc2(){
local flag=1
commands
{
func

myfunc3(){
local flag=0
commands
{
func


szboardstretcher 03-15-2011 12:49 PM

From what I understand, a function will only run if you call it. So, some decent if-then sections, or a 'case' section, and I'm sure there is something that can be done.

Code:

function one (){
commands }
function two (){
commands }
function three (){
commands }

one=0
two=0
three=1

if [ $one -ne 0 ]
then
 one;
fi

if [ $two -ne 0 ]
then
 two;
fi

if [ $three -ne 0 ]
then
 three;
fi


SL00b 03-15-2011 01:19 PM

As said before, you can choose to run particular functions, but one thing I haven't seen yet is how you pass which functions you want to run into the script. This is where command-line arguments come in. Taking the previous example and expanding on it...

Code:

function one (){
commands }
function two (){
commands }
function three (){
commands }


case "$1" in
  1)
        one
        ;;
  2)
        two
        ;;
  3)
        three
        ;;
  *)
        echo "Usage: /path/script.sh {1|2|3}"
        exit 1
esac

If there are cases where you might want to run function 1 and 2, but not 3, you can build those cases into the script as well. For example, I have some scripts to start and stop applications, and I also have a "restart" case that does both.


All times are GMT -5. The time now is 12:25 AM.