Question

I'm trying to make script for multiple input data files. What is the best way, how to handle that arguments? Usage of script should be:

./script.sh -a sth -b sth - c sth -d sth input1 input2 input3    

I can handle parameters and arguments using getopts, but I have no idea, how to handle these input files, because there is no flag for them. Thanks

Was it helpful?

Solution

while getopts ":a:b:c:d:" opt; do
  case "$opt" in
    a) i=$OPTARG ;;
    b) j=$OPTARG ;;
    c) k=$OPTARG ;;
    d) l=$OPTARG ;;
  esac
done
shift $(( OPTIND - 1 ))


for file in "$@"; do
  # your stuff here
done

Please try this, this may solve the purpose for you

My own comment has prompted me to extend the answer:

In case you want to do it only from getopts: You will have to call the script as

./script -a hj -b op -c zx -d some -f "File in list seperated with spaces"

while getopts ":a:b:c:d:f:" opt; do
  case "$opt" in
    a) i=$OPTARG ;;
    b) j=$OPTARG ;;
    c) k=$OPTARG ;;
    d) l=$OPTARG ;;
    f) files=$OPTARG ;;
  esac
done
                      #no shift is required now, since we have file list in $files
for file in $files; do
  # your stuff here
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top