Bash newbie question: I’d like to have this script echo out only users from a given list that are valid user IDs, and not echo the invalid ones.
Here’s what I have so far:
#!/bin/bash while IFS= read -r line do id "$line" if [ $? -eq 1 ] ; then echo $line else echo "$line is not valid user ID" >&2 fi done < "$1"
Instead, it is echoing out the results of ‘id’ as well as the text “is not valid user ID”
uid=17931(wwirls) gid=100000(all_usr) groups=100000(all_usr),12(everyone),62(netaccounts),701(1) wwirls is not valid CruzID id: smak: no such user smak
Ideally, it’d echo results like:
wwirls otheruserid admin
Your help is appreciated!
Advertisement
Answer
id "$line" &> /dev/null
is probably the smallest change that will do what you want. That says to send the output of id
(including any error messages) to the bit bucket (/dev/null
). However, the sense of your test is backwards – $?
is 0
on success, and 1
on failure.
Now, as it happens, if
automatically looks at $?
. So you can shorten this to:
if id "$line" &> /dev/null # Find out if the user exists, without printing anything then echo "$line" # The user exists (`id` succeeded) else echo "$line is not valid user ID" >&2 # No such user fi
Edit 2 If you don’t need the not valid
output, you can replace the whole if
..fi
block with
id "$line" &> /dev/null && echo "$line"
If the command before &&
succeeds, bash runs the command after &&
.