linux - bash 中的错误 - 预期存在 -e 的一元运算符

标签 linux bash

在我使用“read”创建它之后,我想测试两个变量是否存在。如果用户只输入我想要的两个变量之一,它会显示错误。

这是我的代码:

while true;
do
  echo "Saisissez deux variables x et y sous la forme [x y]"
  read x y

  if [ !-e $x ] || [ !-e $y ] <<<<<< problem ligne
  then
    echo "Vous devez renseigner deux nombres x et y"
  elif [ $x = "." ]
  then
    exit 0
  else
    calcul $x $y
  fi
done

当我输入参数时出现错误:

[: !-e: unary operator expected

感谢您的帮助:)

最佳答案

将其更改为:

if [ -z "$x" ] || [ -z "$y" ]

解释

  • [ 实际上是一个内置的 shell(在提示符下尝试 which [help [);它是 test 的同义词。
  • -z[ 的参数。它的意思是“测试下一个字符串的长度是否为 0;如果是则返回 true;否则返回 false。
  • 始终用双引号将您正在测试的变量括起来!

这是 [ 的有用选项列表,因为我认为您会感兴趣:

-b file = True if the file exists and is block special file. 
-c file = True if the file exists and is character special file. 
-d file = True if the file exists and is a directory. 
-e file = True if the file exists. 
-f file = True if the file exists and is a regular file 
-g file = True if the file exists and the set-group-id bit is set. 
-k file = True if the files "sticky" bit is set. 
-L file = True if the file exists and is a symbolic link. 
-p file = True if the file exists and is a named pipe. 
-r file = True if the file exists and is readable. 
-s file = True if the file exists and its size is greater than zero. 
-s file = True if the file exists and is a socket. 
-t fd = True if the file descriptor is opened on a terminal. 
-u file = True if the file exists and its set-user-id bit is set. 
-w file = True if the file exists and is writable. 
-x file = True if the file exists and is executable. 
-O file = True if the file exists and is owned by the effective user id. 
-G file = True if the file exists and is owned by the effective group id. 
file1 –nt file2 = True if file1 is newer, by modification date, than file2. 
file1 ot file2 = True if file1 is older than file2. 
file1 ef file2 = True if file1 and file2 have the same device and inode numbers. 
-z string = True if the length of the string is 0. 
-n string = True if the length of the string is non-zero. 
string1 = string2 = True if the strings are equal. 
string1 != string2 = True if the strings are not equal. 
!expr = True if the expr evaluates to false. 
expr1 –a expr2 = True if both expr1 and expr2 are true. 
expr1 –o expr2 = True is either expr1 or expr2 is true.

关于linux - bash 中的错误 - 预期存在 -e 的一元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13520035/

相关文章:

regex - 使用 sed 更改配置的 Bash 脚本

c++ - GDB 在启动时崩溃(内部错误 : follow_die_offset)

python - Ubuntu 的音量控制通知

bash - 关于备份的 BASH 脚本的建议

bash - 提取字母数字值

linux - 任何人都可以帮我为以下场景编写脚本吗

linux - 移动除一个以外的所有文件夹

c - 对 libncurses 中函数的 undefined reference

php - 命令可以通过 MobaXterm 在 SSH 中运行,但在通过 PHP 的 SSH 中找不到?

json - 将 curl POST 与 bash 脚本函数中定义的变量一起使用