Search code examples
bashshellquoting

Why is there a difference between the output of a Script and a Terminal Command?


Why does bash change the output of my script in comparison to the terminal output?

If I type

dig +noall +answer NS google.com

I get this

But if I do it with a script

#!/bin/bash
echo "Domain: "
read DOMAIN
echo
DIG=$(dig +noall +answer NS $DOMAIN)
echo $DIG

I get this

I want to have the same results as if I typed the command in the console.

I know I could just save and sort (not exactly sort but awk) them in a file but if possible I want to get the same result without having to save the results in a file.

I'm using Ubuntu 16.04 if that helps you


Solution

  • Quote your variables!

    $ DIG=$(dig +noall +answer NS google.com)
    
    $ echo $DIG
    google.com. 86308 IN NS ns2.google.com. google.com. 86308 IN NS ns3.google.com. google.com. 86308 IN NS ns1.google.com. google.com. 86308 IN NS ns4.google.com.
    
    $ echo "$DIG"
    google.com.             86295   IN      NS      ns3.google.com.
    google.com.             86295   IN      NS      ns1.google.com.
    google.com.             86295   IN      NS      ns4.google.com.
    google.com.             86295   IN      NS      ns2.google.com.