0

I want to declare the variable as a command line argument for a shell script just like

./script.sh

file=/tmp/domains.txt 
domain=abcd.com**

help to do the same.

  • which shell are you using? for most shells you can put file=/tmp/domains.txt and domain=abcd.com in a separate file then include it into your script with source whateverfilname. – Skaperen Sep 21 '15 at 11:48
5

You can pass these variables by specifying them before the command name; e.g.

file=/tmp/domains.txt domain=abcd.com ./script.sh

By doing it like this these variables are put into the environment before the shell script is run, meaning that you can use these in the shell script just like any other variables.

| improve this answer | |
1

Passing variables like this works but requires the user to understand the internals of your script. It can also cause weird, seemingly inexplicable behavior if the variables happen to be defined in the environment for some other reason entirely unrelated to your script (and the user forgets to set them on the command line when running your script).

A better way to do it is to use the shell's built-in option parsing, getopts. For example:

usage() {
    # print some help text here, e.g.
    echo Usage:
    echo "      $0 [-f filename] [-d domainname]"
}

# -f and -d are the only valid options and they both
# take strings as arguments.
while getopts f:d: opt; do
  case "$opt" in
     f) file="$OPTARG" ;;
     d) domain="$OPTARG" ;;
     *) usage ; exit 1 ;;
  esac
done
shift $(expr $OPTIND - 1)

# print help message and exit if either file or domain are
# empty.
[ -z "$file" ] && usage && exit 1
[ -z "$domain" ] && usage && exit 1

See your shell's man page (e.g. man bash or man dash) for more details. bash's built in help command also provides useful info about getopts - i.e. help getopts

If you want to be able to use GNU-style long options (e.g. --file, --domain) as well as the short -f and -d, you could use the getopt program from the util-linux package. Note that that's getopt without an "s", while the built-in is getopts with an "s".

I usually use the util-linux getopt because I like to be able to have --long options....but getopts is standard and doesn't require anything extra to be installed because it's built in to every posix compatible shell, and will work with bash, dash, ksh etc.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.