I don't know whether it's possible, but I want to write shell scripts that act like regular executables with options. As a very simple example, consider a shell script foo.sh that is configured to be executable:
./foo.sh
./foo.sh -o
and the code foo.sh
works like
#!/bin/sh
if ## option -o is turned on
## do something
else
## do something different
endif
Is it possible and how to do that? Thanks.
Options are settings that change shell and/or script behavior. The set command enables options within a script. At the point in the script where you want the options to take effect, use set -o option-name or, in short form, set -option-abbrev.
The ability to process options entered at the command line can be added to the Bash script using the while command in conjunction with the getops and case commands. The getops command reads any and all options specified at the command line and creates a list of those options.
Generally, the -f command stands for files with arguments. The command specifies the associated input to be taken from a file or output source from a file to execute a program. The f command uses both -f and -F (follow) to monitor files. In a shell script, -f is associated with the specified filename.
An option is a special kind of argument that modifies the effects of a command. Frequently, you can specify more than one option, modifying the command in several different ways. Some options may be mutually exclusive: you can use one or the other, but not both.
$ cat stack.sh
#!/bin/sh
if [[ $1 = "-o" ]]; then
echo "Option -o turned on"
else
echo "You did not use option -o"
fi
$ bash stack.sh -o
Option -o turned on
$ bash stack.sh
You did not use option -o
FYI:
$1 = First positional parameter
$2 = Second positional parameter
.. = ..
$n = n th positional parameter
For more neat/flexible options, read this other thread: Using getopts to process long and short command line options
this is the way how to do it in one script:
#!/usr/bin/sh
#
# Examlple of using options in scripts
#
if [ $# -eq 0 ]
then
echo "Missing options!"
echo "(run $0 -h for help)"
echo ""
exit 0
fi
ECHO="false"
while getopts "he" OPTION; do
case $OPTION in
e)
ECHO="true"
;;
h)
echo "Usage:"
echo "args.sh -h "
echo "args.sh -e "
echo ""
echo " -e to execute echo \"hello world\""
echo " -h help (this output)"
exit 0
;;
esac
done
if [ $ECHO = "true" ]
then
echo "Hello world";
fi
click here for source
Yes, you can use the shell built-in getopts
, or the stand-alone getopt
for this purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With