I have the following bash function:
lscf() {
while getopts f:d: opt ; do
case $opt in
f) file="$OPTARG" ;;
d) days="$OPTARG" ;;
esac
done
echo file is $file
echo days is $days
}
Running this with arguments does not output any values. Only after running the function without arguments, and then again with arguments does it output the correct values:
-bash-4.1$ lscf -d 10 -f file.txt
file is
days is
-bash-4.1$ lscf
file is
days is
-bash-4.1$ lscf -d 10 -f file.txt
file is file.txt
days is 10
Am I missing something?
Best Answer
Though I can't reproduce the initial run of the function that you have in your question, you should reset
OPTIND
to 1 in your function to be able to process the function's command line in repeated invocations of it.From the
bash
manual:From the POSIX standard:
The "shell invocation" that the
bash
manual mentions is the same as the "single execution environment" that the POSIX text mentions, and both refer to your shell script or interactive shell. Within the script or interactive shell, multiple calls to yourlscf
will invokegetopts
in the same environment, andOPTIND
will need to be reset to 1 before each such invocation.Therefore:
If the variables
file
anddays
should not be set in the calling shell's environment, they should be local variables. Also, quote variable expansions and useprintf
to output variable data: