0

TL;DR How do you assign the text following the command to a variable in bash?

Ex: /path/to/script [value to assign to variable]

I am writing a script that essentially filters out information from a dig and whois in a format that I like. Right now, I have it set assign user input to the variable for the domain I want to query. I am doing this using 'read'. So it looks like:

read -p "Domain:" domain

This requires running the command and then putting in the domain, whereas I would like to put the domain after the command, similar to what you would do when doing a normal dig or whois.

Such as: ./script google.com

I imagine that its not too complicated and that its a matter of redirecting stdin(0) to a variable. Though I am not sure how to do this.

Stephen
  • 63
  • 1
  • 7
  • Usually just a normal `key=value` pair, like `MYVARIABLE=$(read -p "Domain:" domain)` would save the result of `read -p ...` back to MYVARIABLE. – OnlineCop Jun 03 '14 at 18:34
  • http://how-to.wikia.com/wiki/How_to_read_command_line_arguments_in_a_bash_script – Pavel Jun 03 '14 at 18:36
  • With how the 'read' is set up, it's already assigning my input to the variable of $domain without having to do a pair. Id like to be able to just put the domain after the command and have it assign that value to a variable, just so its one step instead of two. – Stephen Jun 03 '14 at 18:40

3 Answers3

0

Arguments on command line are present as $1, $2...

pacholik
  • 8,607
  • 9
  • 43
  • 55
0

You read CLI arguments in bash as ordered index pretty much like AWK.

So if your script is called better-dig.sh, when issuing:

$ better-dig.sh google.com

In your script you must capture the argument google.com within $1, scriptname within $0.

Then:

#!/bin/bash
echo "hi I'm $0 - will call dig with $1"
dig $1 | awk 'the rest of your script'
Marcel
  • 1,266
  • 7
  • 18
0

Commandline arguments are already assigned to variables 1,2,3,4... To access them just use $1, $2. For example

echo "argument one is $1"  

optionally you can assign to another variable

site=$1
totti
  • 321
  • 2
  • 9