1

我需要自学 bash 脚本。我正在阅读这本电子书,它有以下代码:

#!/bin/bash
# hello.sh
# This is my first shell script!

declare -rx SCRIPT="hello.sh"
declare -rx who="/usr/bin/who"
declare -rx sync="/bin/sync"
declare -rx wc="/usr/bin/wc"

# sanity checks

if test -z "$BASH" ; then
    printf "$SCRIPT:$LINENO: please run this script with the BASH shell\n" >&2
    exit 192
fi

if test ! -x "$who" ; then
    printf "$SCRIPT:$LINENO: The command $who is not available - aborting\n" >&2
    exit 192
fi

if test ! -x "$sync" ; then
    printf "$SCRIPT:$LINENO: the command $sync is not available - aborting\n">&2
    exit 192
fi

if test ! -x "$wc" ; then
   printf "$SCRIPT:$LINENO: the command $wc is not available - aborting\n" >&2
   exit 192
fi

USERS = `$who | $wc -l`
if [ $USERS -eq 0 ] ; then
    $sync
fi

exit 0

当我运行它时,我收到以下错误:

hello.sh: line 32: USERS: command not found
hello.sh: line 33: [: -eq: unary operator expected

我真的不知道我做错了什么。我是否不允许以这种方式将用户分配给命令行的输出?如果我在命令行中运行该行,它也不起作用。有任何想法吗?

谢谢

4

3 回答 3

5

删除作业周围的空格=

USERS=`$who | $wc -l`

或者它将被解释为USERS带有两个参数=和 `%who |的命令。$wc -l`

于 2012-05-17T01:26:38.923 回答
4

代替

USERS = `$who | $wc -l`

USERS=`$who | $wc -l`
于 2012-05-17T01:24:54.747 回答
2

在 Bash(实际上在许多 shell 中)中,变量名和符号 = 之间不能有空格

在这种情况下,您需要编写

USERS=`command`  

或者

USERS=$(command)

变量有时充当 C++ 宏。如果变量 USERS 为空并且您键入以下内容:

if [ $USERS -eq 0 ] ; then 

它会被解释为

if [ -eq 0 ] ; then 

并且 -eq 不是一元运算符。为了使它正确,你需要写:

if [ "$USERS" -eq 0 ] ; then 

被解释

if [ "" -eq 0 ] ; then 
于 2012-05-17T01:29:38.373 回答