简体   繁体   English

初学者的Bash脚本:“一元运算符预期”错误&&如何使用grep从命令输出中搜索变量?

[英]Beginner's Bash Scripting: “Unary Operator Expected” error && how to use grep to search for a variable from the output of a command?

I'm attempting to write a bash script that is executed through "./filename username" and checks whether or not that user is logged in, printing the result. 我正在尝试编写一个通过“./filename username”执行的bash脚本,并检查该用户是否已登录,并打印结果。 I'm still new to scripting and am having trouble understanding how to make this work. 我还不熟悉脚本,并且无法理解如何使这项工作成功。

I'm currently getting the error "line 7: [: ambonill: unary operator expected". 我目前得到错误“第7行:[:ambonill:一元运算符预期”。 What does that mean and how can I go about fixing that error? 这意味着什么,我该如何解决这个错误呢?

Additionally, how would I get grep to work instead of sort | 另外,我如何让grep工作而不是sort | uniq? uniq的? I'd like to grep for the variable from the output of the command but can't find anything related in the man page. 我想从命令输出中查找变量,但在手册页中找不到任何相关内容。

#! /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

Try to find a simpler solution, like: 尝试找到一个更简单的解决方案,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM