I'm running a loop querying ldap server for a single dn every time, just to see if it's running okay. I want to output both the successful and unsuccessful responses to a file and while the former works, the latter just gets dumped on a screen and I can't figure out why. This is my code:


for i in $(seq 20000); do
    ldapsearch -x -LLL -D "cn=manager,ou=ft,o=cudb,c=es" -w normal -h -p 389 -b 'dc=IMSI, ou=identities,ou=ft,o=cudb,c=es'
done | while IFS= read -r line; do echo "[---- PL0 ----] $(date) $line"; done >> search_imsi_$(date '+%Y_%m_%d__%H_%M_%S').log 2>&1

I've also tried to pipe the output in the loop (not after done) and error still get's printed on screen. The error in question is:

ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)

The return value of this error is 255.

Is this some special kind of error that doesn't get redirected like the usual ones, or am I missing something?


The message from ldapsearch is being printed to the stderr stream, which is not being caught before the | while.

If you had been trying to redirect it with just a >, that would explain why it wasn't working inside the loop.

If you want to capture ldapsearch's error output, change your script to:


for i in $(seq 20000); do
    ldapsearch -x -LLL -D "cn=manager,ou=ft,o=cudb,c=es" \
      -w normal -h -p 389 \
      -b 'dc=IMSI, ou=identities,ou=ft,o=cudb,c=es' 2>&1    ## <-- added "2>&1" here
done | while IFS= read -r line
  echo "[---- PL0 ----] $(date) $line";  
done >> search_imsi_$(date '+%Y_%m_%d__%H_%M_%S').log      ## no need for 2>&1 here

I reformatted the script a little to make it easier to see the loops and the two changes. Since the second loop is only running an echo statement (to stdout), there's no need to redirect stderr there.

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.