When writing Bash scripts, how can I obtain a value from the command-line when provided as part of option flags in the command line?
For example in the following:
./script --value=myText --otherValue=100
How could I store the myText
and 100
values in the variables $text
and $num
?
-t means: True if file descriptor is open and refers to a terminal. In this case, file descriptor 0 is standard input, so it's checking to see if standard input is coming from the terminals. For a complete list of these file descriptors, run man bash and search for "CONDITIONAL EXPRESSIONS".
The [[ ... ]] part allows to test a condition using operators. Think of it as an if statement. In your example, you're using the -s operator, which tests that the referenced file is not empty. Copy link CC BY-SA 3.0.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
$() means: "first evaluate this, and then evaluate the rest of the line". Ex : echo $(pwd)/myFile.txt. will be interpreted as echo /my/path/myFile.txt. On the other hand ${} expands a variable.
Use getopts.
#!/bin/bash
while getopts ":a:" opt; do
case $opt in
a)
echo "-a was triggered, Parameter: $OPTARG" >&2
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
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