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.

3
  • Usually just a normal key=value pair, like MYVARIABLE=$(read -p "Domain:" domain) would save the result of read -p ... back to MYVARIABLE. Commented Jun 3, 2014 at 18:34
  • how-to.wikia.com/wiki/… Commented Jun 3, 2014 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. Commented Jun 3, 2014 at 18:40

3 Answers 3

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' 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.