bool="$(printf %s\\n "$whois" | grep -q netname:)"
        if $bool;
                echo "netname: is available"    
                echo "netname: is not available"            

I am trying to save whois command information at whois variable. Then on that variable I am searching netname: string and saving the result at bool variable.

But somehow the bool variable always enters true case, although it should not be in this context.

What might be causing this issue?


There are two main problems here:

  • $( takes standard output from a command, not its exit code;
  • if $bool checks if a command with the name matching the data in $bool returns 0, not if the bool is 0 or 1. That is, if $bool contained "foo", the command "foo" would be executed.

Just do the check directly:

if whois | grep -q netname:; then

If you must store the exit code instead of just doing it directly, use [ -eq ,.. ], or the non-POSIX ((:

whois | grep -q netname:

if (( netname_exists == 0 )); then  # Non-POSIX
if [ "$netname_exists" -eq 0 ]; then  # POSIX

If you must store the output from whois for later use too, you can do this:

printf '%s\n' "$whois_data" | grep -q netname:  # or use <<< (non-POSIX) or <<
  • Or whois | grep -q netname:; netname_exists=$? (to save a subshell). Storing return values is pretty desperate once-in-a-career kind of stuff... – Toby Speight Apr 11 '16 at 15:37
  • Thanks Chris, I can directly use whois command in conditional but I want to decrease number of whois queries. Therefore I save the result of whois query in variable and use it in the script many times. I thought "grep -q" would return true or false and I can use it. So if I can keep the code structure like my example but without increasing whois queries, it will be great. – NecNecco Apr 11 '16 at 15:51
  • 2
    @NecNecco In which case, just store the output of whois first and then direct (with printf + pipe, <<, or the non-standard <<<) the output into grep -q. – Chris Down Apr 11 '16 at 15:52
  • Chris, sound great. But could not forge the code myself. Would you mind posting your code as my example please? I will accept your answer. – NecNecco Apr 11 '16 at 16:11
  • 2
    @NecNecco It contains the exit code from the last command of the last pipeline. – Chris Down Apr 14 '16 at 15:42

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.