linux - 初学者的 Bash 脚本 : "Unary Operator Expected" error && how to use grep to search for a variable from the output of a command?

标签 linux bash

我正在尝试编写一个通过“./filename username”执行的 bash 脚本,并检查该用户是否已登录,并打印结果。我对脚本编写还是个新手,无法理解如何使它起作用。

我目前收到错误“第 7 行:[:ambonill:预期的一元运算符”。这是什么意思,我该如何解决该错误?

另外,我怎样才能让 grep 工作而不是 sort |唯一?我想从命令的输出中查找变量,但在手册页中找不到任何相关内容。

#! /bin/bash
# This script will take a username as an argument and determine whether they are logged on.

function loggedin {
   for u in `who | cut -f1 -d" " | sort | uniq`
   do
   if [ $u == $1 ]
   then
      echo "$1 is logged on"
   else
      echo "$1 is not logged on"
   fi
   exit 0
   done
}

loggedin $u
exit 1

最佳答案

尝试找到更简单的解决方案,例如:

#!/bin/bash
echo "$1 is $([ -z "$(w -h $1)" ]&&echo -n not\ )logged on"

关于linux - 初学者的 Bash 脚本 : "Unary Operator Expected" error && how to use grep to search for a variable from the output of a command?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42072229/

相关文章:

Linux - 从 gmail 中继读取电子邮件并运行脚本

使用 sed|awk 和组进行替换的正则表达式

bash - 如何在引用的表达式中转义扩展路径名扩展模式?

c - 串口环回/双工测试,用 Bash 还是 C? (过程替换)

linux - Bash 脚本检查 zip 文件是否为空

regex - 在 sed 中使用 _ .*_ 和 &_

windows - 如何让 Windows 在编译 C++ 时与 Linux 一样快?

linux - grep 字符串中的日期

linux - 回答 golang 中的密码 shell 提示

linux - linux中 `echo ${#str}`是什么意思