首页 > 写一个脚本的时候报错,unary operator expected

写一个脚本的时候报错,unary operator expected

源代码:
1 #!/bin/bash
2
3 if [ $# -ne 1 ];then
4 echo "wrong "
5 exit 1
6 fi
7
8 if [ id $1 ];then
9 echo "user infomation output"
10 sed '/$1/w A.txt' /etc/passwd
11
12 else
13 echo "no such user $1"
14 fi
脚本目的是 判断用户是否存在,存在就提取用户信息,然后添加到其他文件中。
运行后第8行报错 ./Info.sh: line 8: test: id: unary operator expected
百度一下,在8行if后面加一个[] if [[ id $1 ]];then.
但还是报错:
./Info.sh: line 8: conditional binary operator expected
./Info.sh: line 8: syntax error near `"$1"'
./Info.sh: line 8: `if [[ id "$1" ]];then'

本人新手。写脚本不久。电脑win10,wmware12,opensuse42.1 ,xshell5


id是什么东西?也不是个内置变量啊!?


[]实际上就是test,你可以通过man test查看test的文档。一般来说,if会和test组合使用,但并不总是如此。if作用的机制是判断命令的返回值,如果返回值是0就是true,如果非0就是false。

建议阅读ABS,其中就有这样的例子:

if grep hello /etc/passwd ; then
    echo contains hello
else
    echo no hello found
fi

所以应该这样改:

#!/bin/bash

if [ $# -ne 1 ];then
echo "wrong "
exit 1
fi

if id $1 ; then
echo "user infomation output"
sed '/$1/w A.txt' /etc/passwd
else
echo "no such user $1"
fi

[[ -z $(id fengxsong) ]] && echo 'yes' || echo 'no'

类似于大概这样,你没把id的输出结果保存到变量

【热门文章】
【热门文章】