Getopts not echoing correctly

Hi,

When I run the the following code:

#!/bin/bash


if [[ ${#} -lt 1 ]]; then
    usage
fi

if [[ ${UID}  -eq 0 ]]
then
echo "Do not execute this as root, use -s instead"
fi

SERVERFILE="servers"

function usage {
    echo "USAGE: ${0} [-nsv] [-f FILE] COMMAND"
    echo "-f FILE   Use to override the default file"
    echo "-n        Use for dry Run"
    echo "-s        Use to run the command with sudo"
    echo "-v        Use for verbose"
}




#ssh -o ConnectTimeout=2 server01 sudo 

while getopts 'nsvf:' opt
do
    case "${opt}" in
        n)
            shift "$((OPTIND-1))"
            COMMANDS="${*}"
            cat ${SERVERFILE} | while read line 

                do
                echo "DRY RUN ssh -o ConnectTimeout=2 ${line} ${COMMANDS}"
                done
            
            exit 0

        ;;

        s)
            AS_SUDO="YES"
                                  
        ;;

         f)
            
            SERVERFILE=${OPTARG}
        ;;

        v)
            
            echo "verbose mode"
        ;;

    esac
    done
shift "$((OPTIND-1))"

I get the following output:

[vagrant@admin01 vagrant]$ ./new-script.sh -n test-command
 test-commando ConnectTimeout=2 10.9.8.11
 test-commando ConnectTimeout=2 10.9.8.12

I am not sure why is that. Any help will be appreciated.

Your $SERVERFILE has a CR character at the line end (usually from being edited in WinDos).
Run dos2unix on it!

1 Like

You call the "usage" function before it is defined.

I will add after the above posts:
I dont use bash so I may be wrong, but why do you single quotes in the while line?
You use variable I dont see initialised so no idea what they contain
I have never seen a shift out of a case ( here after done...)
So I suspect you have not given us the whole script so cant guess with what we have here...

Perfect. Retested it and it's working as expected.

Thanks