Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash variable from command with pipes, quotes, etc

I have a command I'm using to get the hostname.localdomain:

dig axfr @dc1.localdomain.com localdomain.com | grep -i Lawler | awk '{ getline ; $1=substr($1,1,length($1)-1); print $1 ; exit }'

This nicely returns a result like:

michael.lawler.localdomain.com

I'd like to further use that result as a variable in a Bash script.

It seems I'm having trouble getting past the first pipe.

If I VAR="dig axfr @dc1.localdomain.com localdomain.com | grep -i Lawler | awk '{ getline ; $1=substr($1,1,length($1)-1); print $1 ; exit }'"

...I get back the entire zone transfer. I've also tried many minor changes, adding $ before the dig command, without quotes, but nothing seems to work. How can I fix this?

like image 935
TryTryAgain Avatar asked Mar 06 '13 19:03

TryTryAgain


People also ask

What does the Bash command output to the variable?

BASH command output to the variable. Different types of bash commands need to be run from the terminal based on the user’s requirements. When the user runs any command from the terminal then it shows the output if no error exists otherwise it shows the error message.

How to print the output of `pwd` command in bash script?

The following script stores the output of `pwd` command into the variable, $current_dir and the value of this variable is printed by using `echo` command. The option and argument are mandatory for some bash commands.

What is quoting in bash scripting?

Quoting in bash scripting is a process to make variables or any other container for data to be expanded to the literal value inside any string, quoting is also used for other operations as well. There are several types of quoting techniques in a bash script.

How do I see the environment variables in a bash script?

To see the active environment variables in your Bash session, use this command: env | less. If you scroll through the list, you might find some that would be useful to reference in your scripts. How to Export Variables. When a script runs, it’s in its own process, and the variables it uses cannot be seen outside of that process.


2 Answers

VAR=$( dig axfr @dc1.localdomain.com localdomain.com |
     grep -i Lawler |
     awk '{ getline ; $1=substr($1,1,length($1)-1); print $1 ; exit }' )
like image 137
William Pursell Avatar answered Oct 18 '22 01:10

William Pursell


Use backtics instead of quotes:

VAR=`dig axfr @dc1.localdomain.com localdomain.com | grep -i Lawler | awk '{ getline ; $1=substr($1,1,length($1)-1); print $1 ; exit }'`

Backtics actually mean "run whatever is in here and return standard out as the expression's value", but quotes don't do that.

like image 33
bchurchill Avatar answered Oct 18 '22 01:10

bchurchill