1

In a shell script, possibly bash, how can we take many of the same type of argument and add them to an internal array? An example would be like so:

./combine -f file1 -f file2 -f file3 -o output_file

I am aware this simple problem can be solved with cat and redirection alone. But I am interested in how in lets say bash we can take all three of the -f arguments and have them in an array so we can do something with them?

Due to the nature of the requirement we need some form of flags here since there will be other arguments.

In a language like python it is rather easy, especially with library like docopt. You can specify an array as intended and you are done.

Thanks so much

Biff
  • 312
  • 2
  • 3
  • 9

1 Answers1

6

you can use getopts:

#!/bin/bash

while getopts "f:o:" opt; do
    case $opt in
        f) file+=("${OPTARG}") ;;
        o) output="${OPTARG}" ;;
        *) exit 1 ;;
    esac
done
shift $((OPTIND-1))

echo "List of files: \"${file[@]}\""
echo "Output: \"$output\""

so for example:

$ bash test.sh -f 1 -f 2 -f three -o /dev/null
List of files: "1 2 three"
Output: "/dev/null" 

so what i'm doing is adding every occurance of each -f flag to an array file and then simply printing it. as for -o i'm just saving the input to a variable output. anything else will result in the stderr of getopts and exit:

$ bash test.sh -w hi
test.sh: illegal option -- w
$ echo $?
1                       
Community
  • 1
  • 1
odradek
  • 993
  • 7
  • 14