I am writing a bash program that takes options.
For example : ./my_program -l 3 -a -s
-l 3will limit the output to three lines-awill select all my file-swill sort the output
For now, I could use two options at a time this way:
if [ $all == 1 ]
then
if [ $sort == 1 ]
then
printf '%s\n' "${haikus[@]}" | sed -e 's/^[ \t]*//' | sort
else
printf '%s\n' "${haikus[@]}" | sed -e 's/^[ \t]*//'
fi
fi
If -a option, I print the whole file, or, if -a option and -s option, I use the same command but i use sort.
With this solution, if I want to implement the -l, it would create a lot of "if" statements.
I first thought of creating a variable containing my command.
Example:
sort='sort'
limit='grep -m3'
and then write my command this way:
printf '%s\n' "${haikus[@]}" | sed -e 's/^[ \t]*//' | $sort | $limit
But that is simply not working.
The fact is, I would like to write a basic command, and being able to add more to this one, depending of the options.
How can I do this properly without tons of "if" statements?
==in[is not guaranteed to work in all POSIX-compliant shells. It's more reliable to use=for string comparison, as it's required to work by the POSIX standard fortest, and correspondingly works even with minimal/bin/shimplementations, not just bash.