make a script take options
Read a script's arguments and options, and stop with a usage line when they are wrong.
shelldevelopment
steps
-
echo "$1 $2 ($# arguments)"the first two arguments, and how many there are
-
[ $# -eq 0 ] && { echo "usage: $0 FILE"; exit 1; }stop when none were given
-
for arg in "$@"; do echo "$arg"; donego through every argument, spaces kept
-
while getopts 'vf:' opt; do case $opt in v) verbose=1;; f) file=$OPTARG;; *) exit 1;; esac; done-v and -f FILE options
-
shift $((OPTIND - 1))after getopts: what is left are the plain arguments
-
name="${1:-world}"a default when no argument was given
commands used
getoptsshift
Each has a page in lore: lore getopts opens it.
ask for input in a script
Ask yes or no, read a password without showing it, or wait for an answer with a time limit.
check if a file or folder exists
Test in a script whether a path exists, is a file, a folder, empty or runnable.
check if a string contains a text
Test in a script whether a string contains, starts with or matches something.
find the script's own folder
Inside a script, find the folder the script is in, to reach files next to it.