Search code examples
bashgetopts

How can I get filename and argument with getopts from Command


Here is the code, I want to run this command
Getting the test.log input, then convert it to text type, then store it on the output.txt file

./small.sh test.log -t text -o output.txt

#!/usr/bin/env bash

usage() { echo "$0 usage:" && grep " .)\ #" $0; exit 0; }
[ $# -eq 0 ] && usage

parse()
{
        local file=$1
        local type=$2
        local output=$3

        echo "file: ${file}, type: ${type}, output: ${output}"
}

while getopts ":ht:o:" arg; do
  case $arg in
    t) # specify type.
      type=${OPTARG} ;;
    o) # specify directory.
      output=${OPTARG} ;;
    h | *) # Display help.
      usage
      exit 0
      ;;
  esac
done

shift $(( OPTIND - 1))
parse "${file}" "${type}" "${output}"

with this code i can only get filename when i put it in unsort order like this ./small.sh -t text -o output.txt test.log


Solution

  • How can I get filename and argument with getopts

    ./small.sh test.log -t text -o output.txt
    

    It is not possible. getopts only supports positional arguments after option arguments.

    You can:

    • accept the limitation
    • use something elsem, like GNU getopt.
    • write your own option parsing code