0

I am working on an assignment that requires me to accept user input to search for current users on the server and if the user input is online, I need to output the users name. If the user is not logged in I need to respond accordingly. I have been working on this code for days and can't seem to figure it out. I can search for the user but when it comes to comparing my user input variable string with the variable string holding the users name who is logged in I keep getting an error that says too many arguments. Please see my code below:

#!/bin/bash
read -p "Please enter the user name you would like to search: " userName
name=$(who | grep "${userName}" | awk '{print $1}');
if  [ [  $name == *"$userName"* ] ];
then
        echo $name
else
        printf "That user is not logged in.\n";
fi
0

You're close, but the main problem is the bash [[ ]] construct can't have spaces in between the brackets. It think's you're trying to do multiple [ commands, which is the POSIX test command. If you fix that it works, but if the user has multiple ttys open is will print their name once for every one. If you want to use grep, you can do this:

#!/bin/bash

read -p "Please enter the user name you would like to search: " userName
if who | awk '{print $1}' | grep -wq "$userName"
then
  echo "$userName is logged in."
else
  echo "That user is not logged in.";
fi

exit
  • Thank you so much, this worked. Linux is so sensitive, I will definitely keep practicing on my formatting. – codenewbie503 Dec 4 '17 at 8:07
  • This page helped me a lot when learning Bash. The rest of the site is a great reference, too. mywiki.wooledge.org/BashPitfalls – m0dular Dec 4 '17 at 16:20

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.