Home > front end >  i am getting [: argument excepted in unix command
i am getting [: argument excepted in unix command

Time:09-17

I have a code similar to below:

while [ $k = 0 ];
do
if [ $Year1 = $Year2 ] && [  $Month1 = $Month2 ]; then
  echo "abcd"
else
  echo"erty"

The error is line highlighted line > line 144]: [: argument expected

CodePudding user response:

At least one of your variables contains unexpected data (e.g. is empty, or has spaces or new line characters), causing the [ command to not receive the arguments it expects.

Always quote your variables ("$Year1" instead of $Year1) to avoid surprises like this one.

CodePudding user response:

while [ "$k" = 0 ]; do if [[ $Year1 == $Year2 && $Month1 == $Month2 ]]; then echo "abcd"; else echo "erty"; fi; done

Helpfull could be: https://www.shellcheck.net

CodePudding user response:

You should use == for comparisons instead of = and also please use -eq whenever you want to use == if your code is for integer comparison. For example,

if [ $FLAG -eq 1 ];then

For strings, you can use =, like for example NOTE : Edited as pointed by Sir Athos

if [ "$Year1" = "$Year2" ] && [ "$Month1" = "$Month2" ]; then

or if you are comparing variable with string then, you can also use ==,

if [ "$STA" == "Completed" ];then

Adding test script to further clarify :

-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$ 
  • Related