The main problem is here:
read $input
In bash, usually, $foo
is the value of the variable foo
. Here, you don't want the value, but the name of the variable, so it should be just:
read input
Similarly, in the if
tests, $yes
and $no
should be just yes
and no
, since you just want the strings yes
and no
there.
You could use a case
statement here, which (IMHO) makes it easier to do multiple cases based on input:
case $input in
[Yy]es) # The first character can be Y or y, so both Yes and yes work
echo "Hello!"
echo "Hello!" | festival --tts
;;
[Nn]o) # no or No
echo "Are you sure?"
echo "Are you sure?" | festival --tts
;;
*) # Anything else
echo "Please answer yes or no."
echo "Please answer yes or no." | festival --tts
;;
esac
You could wrap the two echo
statements and the use of festival
in a function to avoid repeating yourself:
textAndSpeech ()
{
echo "$@"
echo "$@" | festival --tts
}
case $input in
[Yy]es) # The first character can be Y or y, so both Yes and yes work
textAndSpeech "Hello!"
;;
[Nn]o) # no or No
textAndSpeech "Are you sure?"
;;
*) # Anything else
textAndSpeech "Please answer yes or no."
;;
esac
With $input
, bash replaces this with its value, which is nothing initially, so the read
command run is:
read
And read
by default stores the input in the variable REPLY
. So you can, if you want, eliminate the input
variable altogether and use $REPLY
instead of $input
.
Also have a look at the select
statement in Bash.
To modfy your current approach, you would need an array of counters for the different users, and an additional loop to test each value of $users
against each positional parameter $1
, $2
, ... .
Note that for users in $(w -h)
loops over all the whitespace-delimited tokens in the output of w -h
, not just the usernames - it may "work" (because it's unlikely that other tokens match a valid username) but it's not "right" - you could use $(w -h | cut -d ' ' -f1)
to extract just the usernames.
For a simpler approach, you could run w -h
for each username given on the command line, and count the number of lines of output, for example using wc -l
#!/bin/sh
for user do
counter=$(w -h "$user" | wc -l)
if [ "$counter" -gt 2 ]; then
printf "user %s is logged in %d times\n" "$user" "$counter"
else
printf "user %s is logged in less than two times\n" "$user"
fi
done
Note that bash
is not necessary for this - you can use the lighter /bin/sh
shell (although the same code will run in bash).
Best Answer
You can use the
who -u
command to list the users who are logged in. Then you could usegrep
to look for a specific user in the output, and exit with success if found, or exit with failure otherwise.(Thanks to @dessert for shortening the
who -u | ...
part!)