Home > Blockchain >  How to make it manditory for options to be spaced for bash scripts
How to make it manditory for options to be spaced for bash scripts

Time:11-13

I have the following script.

I would like to modify it so that if I were to call temp.sh with both the options, I would have to space them. Ie: A call to the script like temp.sh -fc30 should be invalid, rather it should be temp.sh -f -c 30

     ARGS=$(getopt -o c:f -l "charlie:fox" -n "temp.sh" -- "$@");

    
    #bad args
    if [ $? -ne 0 ];
    then
        exit 1
    fi
    
    eval set --"$ARGS";
    
    while true; do  
        
        case "$1" in
            -c|--charlie)
                shift;
                if [ -n "$1" ]; then
                    echo "-c =: $1";
                    shift;
                fi
                ;;  
            -f|--fox)
                shift;
                echo "fox used";
                ;;      
            
            
            --)
                shift;
                break;
                ;;
        esac
    done

CodePudding user response:

Just don't use getopt.

#!/bin/bash

# parse options

while [[ $# -gt 0 ]]; do
    case $1 in
        -c|--charlie)
            echo "$1 = $2"
            shift
        ;;
        -f|--fox)
            echo "fox used"
        ;;
        --)
            shift
            break
    esac

    shift
done

# do script
  • Related