Search code examples
bashshellargumentsgetopts

Bash script - last case in getopts not getting read


I have the following bash script

#!/bin/bash

id=""
alias=""
password=""
outputDirectory=""
extension=""

function ParseArgs()
{
while getopts "t:a:p:f:r:o:e" arg
do
case "$arg" in
t)
id=$OPTARG;;
a)
alias="$OPTARG";;
p)
password="$OPTARG";;
f)
folderPath="$OPTARG";;
r)
relativeFolderPath="$OPTARG";;
o)
outputDirectory="$OPTARG";;
e)
extension="$OPTARG";;
-)      break;;
esac
done
}

ParseArgs $*

echo "Getting all input files from $folderPath"
inputFiles=$folderPath/*

echo "Output is $outputDirectory"
echo "Extension is $extension"
if [[ $extension != "" ]]
then
    echo "Get all input files with extension: $extension"
    inputFiles = $folderPath/*.$extension
fi

for file in $inputFiles
do
    echo "Processing $file"
done

For some reason, the last argument (-e) doesn't get read if I use it. For example, I get the same output below with or without the last argument (-e xml), I was testing it by including outputDirectory to make sure it does get read.

sh mybashscript.sh -t 1 -a user -p pwd -o /Users/documents -f /Users/documents/Folder -r documents/Folder/a.xml -e xml
Getting all input files from /Users/dlkc6428587/documents/ResFolder
Output is /Users/documents
Extension is 
Processing /Users/documents/Folder/a.xml
Processing /Users/documents/Folder/b.xml

It's really weird, does anyone know what I am doing wrong? Thank you.


Solution

  • You haven't indicated that -e takes an argument by following it with a colon in the call to getopts:

    while getopts "t:a:p:f:r:o:e:" arg
    

    Also, you should call the function like this

    ParseArgs "$@"
    

    to ensure that any arguments containing whitespace are handled properly.


    And finally, inputFiles should be an array:

    inputFiles=( "$folderPath"/*."$extension" )
    
    for file in "${inputFiles[@]}"
    do
        echo "Processing $file"
    done