linux - 写一个脚本的时候报错,unary operator expected
PHP中文网
PHP中文网 2017-04-17 15:02:33
0
3
871

源代码:
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

PHP中文网
PHP中文网

认证0级讲师

全部回覆(3)
伊谢尔伦

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

類似大概這樣,你沒把id的輸出結果存到變數

Ty80

[]其實就是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  ; then
echo "user infomation output"
sed '//w A.txt' /etc/passwd
else
echo "no such user "
fi
伊谢尔伦

id是什麼東西?也不是個內建變數啊! ?

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!