首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我在unix命令中得到[:argument excepted

我在unix命令中得到[:argument excepted
EN

Stack Overflow用户
提问于 2021-09-15 10:40:35
回答 3查看 47关注 0票数 0

我有一个类似于下面的代码:

代码语言:javascript
运行
复制
while [ $k = 0 ];
do
if [ $Year1 = $Year2 ] && [  $Month1 = $Month2 ]; then
  echo "abcd"
else
  echo"erty"

错误为行突出显示的行>第144行]:[:预期的参数

EN

回答 3

Stack Overflow用户

发布于 2021-09-15 10:59:05

您的变量中至少有一个包含意外数据(例如,为空、包含空格或换行符),从而导致[命令无法接收预期的参数。

总是引用你的变量("$Year1"而不是$Year1),以避免像这样的意外。

票数 1
EN

Stack Overflow用户

发布于 2021-09-15 10:58:29

代码语言:javascript
运行
复制
while [ "$k" = 0 ]; do if [[ $Year1 == $Year2 && $Month1 == $Month2 ]]; then echo "abcd"; else echo "erty"; fi; done

Helpfull可以是:https://www.shellcheck.net

票数 0
EN

Stack Overflow用户

发布于 2021-09-15 10:50:42

您应该使用==而不是=进行比较,如果您的代码用于整数比较,请随时使用-eq。例如,

代码语言:javascript
运行
复制
if [ $FLAG -eq 1 ];then

对于字符串,您可以使用=,例如NOTE :按照Athos爵士的指示进行编辑

代码语言:javascript
运行
复制
if [ "$Year1" = "$Year2" ] && [ "$Month1" = "$Month2" ]; then

或者,如果要将变量与字符串进行比较,也可以使用==

代码语言:javascript
运行
复制
if [ "$STA" == "Completed" ];then

添加测试脚本以进一步阐明:

代码语言:javascript
运行
复制
-bash-4.2$ cat string.sh
#!/bin/bash -x

str1="Hello There"
str2="Hello There"

if [ "$str1" = "$str2" ];then
        echo "Matched"
else
        echo "Not Matched"
fi

if [ "$str1" == "Hello There" ];then
        echo "Matched"
else
        echo "Not Matched"
fi

-bash-4.2$ ./string.sh 
+ str1='Hello There'
+ str2='Hello There'
+ '[' 'Hello There' = 'Hello There' ']'
+ echo Matched
Matched
+ '[' 'Hello There' == 'Hello There' ']'
+ echo Matched
Matched
-bash-4.2$ 
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69191536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档