Search code examples
androidbashshellgetoptgetopts

Using getopt(s) to run specific parts of script when parameter is passed at runtime


I've written a long bash script for configuring an SSH daemom, etc on android. Problem is, it has gotten too long & at times other users or I may only want to configure certain aspects of what the script has to offer. Instead of having to go through entire script each time it is ran I would like to add options that dictate what will be ran but still be able to run script as whole when nothing is specified.

Something like:

myscript -d -o -p

Or

myscript -dop    

The script can be found here. I think its too long to be posted here.

Basically it's broke up into 5 blocks like this:

#!/system/xbin/bash

echo "---SECTION-ONE---"

read
if test then  

while true
do

I looked up using getopts and can't quite wrap my head around it just yet without an example that matches with what I'm doing. Thats why I'm posting here ;) As always thanks for any inpout.


Solution

  • You can break down the different bodies of the script into functions that can be called when an option is present.

    #!/bin/bash
    
    printing_stuff (){
        echo "---SECTION-ONE---"
    }
    
    test_input (){
        read -p "Enter something: " input
        if [[ $input == something ]]; then
            echo "test successful"
            # do some stuff
        fi
    }
    
    body_loop (){
        while true; do
            echo "this is the loop"
            # some stuff
            break
        done
    }
    
    if [[ $@ ]]; then
        while getopts "dop" opt; do
            case $opt in
                d)
                    printing_stuff
                    ;;
                o)
                    test_input
                    ;;
                p)
                    body_loop
                    ;;
                \?)
                    ;;
            esac
        done
    else
        printing_stuff
        test_input
        body_loop
    fi
    

    The [[ $@ ]] test is done to only run the getopts loop if arguments to the script exist, otherwise run everything.