Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Bash, how can option flag values be stored in variables? [duplicate]

Tags:

bash

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?

like image 329
BWHazel Avatar asked Oct 21 '11 15:10

BWHazel


People also ask

What does the flag do in bash?

-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".

What does [[ ]] mean in bash?

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.

What does $_ mean in bash?

$_ (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.

What is $() in bash?

$() 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.


1 Answers

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
like image 178
ggiroux Avatar answered Oct 13 '22 12:10

ggiroux