linux - 使用 grep 和 cut 过滤 who 的输出

标签 linux bash

我有这个练习:

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/

相关文章:

regex - 如何通过保持目录结构完整来同步路径中具有匹配模式的文件?

linux - 删除原始文件夹时删除符号链接(symbolic link)

linux - docker镜像的环境变量写在哪里?

linux - 在 Unix/Linux 平台中查找操作系统名称和版本的最佳方法

linux - 如何为 RISC-V 编译 Linux Kernel 4.20

c# - Process.Start 崩溃无一异常(exception)

git - 通过命令行在 Git 提交消息中使用撇号(单引号)

bash - 为什么测试会说意外的括号?

c++ - 如何在 Linux 上使用 Boost.Filesystem?

linux - 生成特定的非零返回码?