我有这个练习:
Create a bash script that check if the user passed as a parameter is connected and if he is display when he connected. Indications : use the command who, the grep filter and the command cut.
但是我有一些麻烦来解决它。
#!/bin/bash
who>who.txt;
then
grep $1 who.txt
for a in who.txt
do
echo "$a"
done
else
echo "$1 isnt connected"
fi
所以首先我只想保留我可以在 .txt 中找到用户的那一行,然后我想在 who 命令中用循环剪切每个部分以只保留日期,但问题是我不知道如何在这里剪切,因为它是用多个空格分隔的。
所以我真的被封锁了,我不知道该去哪里做这件事。我是 bash 的初学者。
最佳答案
如果我理解您只是想检查用户是否登录,那么这就是 users
命令的用途。如果您想将它包装在一个简短的脚本中,那么您可以执行以下操作:
#!/bin/bash
[ -z "$1" ] && { ## validate 1 argument given on command line
printf "error: insufficient input, usage: %s username.\n" "${0##*/}" >&2
exit 1
}
## check if that argument is among the logged in users
if $(users | grep -q "$1" >/dev/null 2>&1) ; then
printf " user: %s is logged in.\n" "$1"
else
printf " user: %s is NOT logged in.\n" "$1"
fi
示例/使用
$ bash chkuser.sh dog
user: dog is NOT logged in.
$ bash chkuser.sh david
user: david is logged in.
关于linux - 使用 grep 和 cut 过滤 who 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724195/