I am trying to setup a script that will test for a user and if it doesn’t exist I will add the user to a server. For now I am just testing to see if what I am testing for is found and I can do different actions based on what is returned. When I do echo "$BOBCHECK"
after the ssh command I do get either found or missing results back as it runs through my server list so I know that part is working as expected and I have my variable set within the loop cycle. However the only result I get for the if tests is the failed test echo of “exist check failed” like the variable has been reset inside the if statements. Can someone explain what I am doing wrong here?
#!/bin/bash
#
#
for hn in $(cat /root/scripts/linux/linhosts.lst); do
echo "" && echo "Checking for bob user on $hn" && BOBCHECK=$( ssh -t -oStrictHostKeyChecking=no "$hn" 'if getent passwd bob > /dev/null 2&>1; then echo "found"; else echo "missing"; fi' )
echo "$BOBCHECK"
if [ "$BOBCHECK" = "found" ]; then
echo "exist check complete, user found"
elif [ "$BOBCHECK" = "missing" ]; then
echo "exist check complete, user not there"
else
echo "exist check failed"
fi
done
Example output from the script running:
Checking for bob user on server42
Connection to server42 closed.
missing
exist check failed
Checking for bob user on server43
Connection to server43 closed.
missing
exist check failed
Checking for bob user on server44
Connection to server44 closed.
found
exist check failed
I have tried double brackets, double equals, nested if statements instead of elif statements, all with the same result. I even tried “-eq” which I quickly found only works for integers and not strings.
11
If you use ssh
with -t
, it treats output as a terminal and expands n
to rn
.
Consider (with bash printf):
$ printf '%qn' "$(ssh -t user@host echo hmmm 2>/dev/null)"
$'hmmmr'
To avoid this, don’t use -t
:
$ printf "%qn' "$(ssh user@host echo ok)"
ok
Since getent
probably doesn’t ever exit with 255, and ssh
exits with the exit status of the remote command executed, you could write:
#!/bin/bash
#
#
for hn in $(cat /root/scripts/linux/linhosts.lst); do
echo "" && echo "Checking for bob user on $hn"
ssh -t -oStrictHostKeyChecking=no "$hn" 'getent passwd bob >/dev/null 2&>1'
case $? in
255) echo "ssh failed" ;;
0) echo "exist check complete, user found" ;;
2) echo "exist check complete, user not there" ;;
*) echo "exist check failed" ;;
esac
done