I don't understand the shift
in following code:
#! /usr/local/bin/bash
# process command line options
interactive=
filename=
while [[ -n $1 ]]; do
case $1 in
-f | --file) shift #don't understand the shift #No.1
filename=$1 ;;
-i | --interactive) interactive=1
;;
-h | --help) usage
exit;;
*) echo "usage >&2 exit 1";;
esac
shift # don't understand the shift #2
done
#interactive mode
if [[ -n $interactive ]]; then
echo "do something"
fi
#output html page
if [[ -n $filename ]]; then
if touch $filename && [[ -f $filename ]]; then
echo "write_html_page > $filename" #debug
else
echo "$program: Cannot write file $filename " >&2
exit 1
fi
else
echo "write_html_page to terminal" # debug
fi
Test it
$ bash question.sh -f test
write_html_page > test
$ bash question.sh -f
write_html_page to terminal
When I delete shift
and change filename=$1
to filename=$2
$ bash question.sh -f
write_html_page to terminal
# it works properly
$ bash question.sh -f test
usage >&2 exit 1
write_html_page > test
# it almost function nicely except that `usage >&2 exit 1` is executed.
So the shift
cannot be replaced by filename=$2
entirely.
The second shift at the botton if deleted, the loop run endlessly.
Could I interpret shift
intuitively?
I did't find such a magic command in other languages.