0

I want find servers that not using "net" command. So, I'll run a script from remote. The script is like that:

for ip in $(cat ip_list_file)
do
    netCom=$(ssh -o ConnectTimeout=2 -o StrictHostKeyChecking=no -o PasswordAuthentication=no $ip "net ads info | grep -i command | wc -l")
    if [ $netCom -eq 1 ]
    then 
        echo -e $ip >> not_installed
    else
        echo -e $ip >> installed
    fi
done

But I have a problem at "net ads info | grep -i command | wc -l" command, because I was thinking I can use "bash: net: command not found..." sentence but I can't. I don't want reverse my script like find installed. My question is this: How can I use grep command for the outputs like "bash: net: command not found..."?

2
  • This looks like XY problem. More proper way is to check if the exit code is 127 (see this) or to use type (bash builtin), e.g. type -P net. Aug 3, 2017 at 9:35
  • Actually it's not XY problem. But the main problem is more bigger than this. So I just asked this part with some changes. Maybe the example was bad. Aug 3, 2017 at 14:32

1 Answer 1

2

The error message is printed to stderr, so you need to redirect it to stdout instead, in order for grep to find it.

for ip in $(cat ip_list_file)
do
    netCom=$(ssh -o ConnectTimeout=2 -o StrictHostKeyChecking=no -o PasswordAuthentication=no $ip "net ads info 2>&1 | grep -i command | wc -l")
    if [ $netCom -eq 1 ]
    then 
        echo -e $ip >> not_installed
    else
        echo -e $ip >> installed
    fi
done
2
  • Thanks. What is the meaning of "2>&1"? I can understood redirecting but how is work "2>&1"? Aug 3, 2017 at 11:31
  • 1
    2>&1 means roughly "redirect file handle 2 to file handle 1" (2 being stderr and 1 being stdout). So everything written to stderr gets instead written to stdout.
    – Magnus
    Aug 3, 2017 at 11: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.