Bash: get directory argument
I am writing a bash script that uses the call syntax
script [options] [dir]
To get a set of parameters and parse them, I use getopts. But how can I get the dir argument? In general, if I receive the last argument as $ {@: $ {# @}}, it does not have to be a director, it can still be an option or a value.
The code I'm using for getopts:
DIR="."
RECURSIVE=
FILTER=
while getopts "hnf:" OPTION
do
case $OPTION in
h)
usage
exit 1
;;
n)
RECURSIVE="-maxdepth 1"
;;
f)
FILTER=$OPTARG
;;
\?)
exit 1
;;
:)
exit 1
;;
esac
done
You can help?
+3
source to share
2 answers
DIR=
RECURSIVE=
FILTER=
while getopts ':hnf:' OPTION ;do
case $OPTION in
h) usage; exit 1 ;;
n) RECURSIVE="-maxdepth 1" ;;
f) FILTER=$OPTARG ;;
*) echo "ERROR: invalid opion: -$OPTARG" 1>&2; exit 1 ;;
esac
done
# remove the options from the positional parameters
shift $((OPTIND-1))
DIR="$1"
echo "FILTER=$FILTER"
echo "DIR=$DIR"
Command line example
script -n -f 'my.*filter' 'my/directory'
Output example
FILTER=my.*filter
DIR=my/directory
0
source to share