我正在尝试编写一个bash脚本,该脚本通过“./filename username”执行,并检查该用户是否已登录,并打印结果。我对脚本编写还不太熟悉,而且很难理解如何使它工作。
我当前收到错误“行7:[:ambonill:unary operator expected”。这意味着什么,我怎样才能解决这个错误呢?
另外,我怎样才能让grep代替uniq工作呢?我想从命令的输出中获取变量,但在手册页中找不到任何相关的内容。

#! /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脚本:“期望一元运算符”错误&&如何使用grep从命令输出中搜索变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42072229/

10-16 12:25