1

Suppose we only have 1 parameter

host $1

How can I check if the above command will give me an answer or:

Host $1 not found (NXDOMAIN) 

and instead of showing an error not found, I would like to show just a -

2

host will exit 1 if it is unable to resolve your input so you can use an if construct:

if ! host "$1" | grep -v 'not found'; then
  printf '%s\n' '-'
fi

We are using ! to test if the command fails (since I assume you want to just print the output as normal if it passes). host sends the not found error to stdout instead of stderr so we can't just hide stdout. This is why I am piping the host command into grep -v 'not found' this will hide the not found error if it exists and still exit 1, causing the if construct to print -. If it does not find not found it will exit 0.

  • i dont know if i type anything wrong but now it just prints both of them: Host $1 not found (NXDOMAIN) - – Thodoris Diamantidis Jun 5 at 14:48
  • @ThodorisDiamantidis: Yes sorry, it appears as if host sends errors to stdout instead of stderr – Jesse_b Jun 5 at 14:49
  • Ok this solution seems to work just fine thank you a lot. – Thodoris Diamantidis Jun 5 at 14:52
0

Would exit status be sufficient? You can incorporate the $?, the exit status of last command, even if you silenced the output. For host exit status 0 is success and 1 is error

[17:54] [ws ~] $ host 127.0.0.112 1>&2 >/dev/null
[17:54] [ws ~] $ echo $?
1
[17:54] [ws ~] $ host 127.0.0.1 1>&2 >/dev/null
[17:54] [ws ~] $ echo $?
0

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.