简体   繁体   中英

Editing Bash Script To Display Output

I have a script that cycles through several servers and if a particular user is found it will output their name. I'd like to modify the individual statements so that if a user isn't found ' NO USER IDENTIFIED ' is output.

Here is an individual code snippet:

echo "environment1" sshpass -p $ldappw ssh $ldapuser@12.34.567.65 'mysql -h website.com -u topuser -ppassword dbname-e "select concat(FIRST,LAST) from users;"' | grep -i ${username}

I would appreciate the assistance of the community in modifying the statement to give me the desired output.

One simple solution is to just write this:

echo "environment1" sshpass -p $ldappw ssh $ldapuser@12.34.567.65 'mysql -h website.com -u topuser -ppassword dbname-e "select concat(FIRST,LAST) from users;"' | (grep -i ${username} || echo "NO USER IDENTIFIED")

Explanation

As Etan points it out, grep returns failure if no lines are selected. This is what the grep manual says on that:

The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2.

Bash evaluates the right side of || only if the left side was false. As the bash manual says:

The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.

So if grep cannot select a row which matches ${username} , echo will do the job.

Notes

  • Consider selecting only the desired user select concat(FIRST,LAST) from users where concat(FIRST,LAST) like '%${username}%;' . With this trick you can do an exact match before grep (just remove % characters from the like).
  • Consider using the -N (Do not write column names in results.) and the -s (Silent mode.) parameters of mysql, so it produces less output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM