how to check if $1 and $2 are null?












35















I am running some script which passing the string argument and I want to do if else statement shown as below:



if [ $1 != '' ] && [ $2 != '' ]
then
do something.....


but it shown Error too many argument. Why?










share|improve this question

























  • You should provide 1. the command which you call the script and 2. the full output.

    – Lucio
    Apr 7 '14 at 3:46






  • 2





    You should use [[ ]]. Otherwise you have to quote your variables.

    – Christophe De Troyer
    Jan 8 '15 at 22:48











  • If $1 didn't exist then $2 would become $1 which makes the test of $1 and $2 both being null seem irrelevant.

    – WinEunuuchs2Unix
    Dec 25 '16 at 2:18











  • @WinEunuuchs2Unix Not necessarily irrelevant - in some cases you want to ensure there's actually something instead of blank or null string in arguments. $1 could be unset or set to null string by user of the script. Consider this sequence of command: $ set '' bar then echo "x${1}x"; Both variables are set, but one of them is null.

    – Sergiy Kolodyazhnyy
    Dec 3 '18 at 5:54
















35















I am running some script which passing the string argument and I want to do if else statement shown as below:



if [ $1 != '' ] && [ $2 != '' ]
then
do something.....


but it shown Error too many argument. Why?










share|improve this question

























  • You should provide 1. the command which you call the script and 2. the full output.

    – Lucio
    Apr 7 '14 at 3:46






  • 2





    You should use [[ ]]. Otherwise you have to quote your variables.

    – Christophe De Troyer
    Jan 8 '15 at 22:48











  • If $1 didn't exist then $2 would become $1 which makes the test of $1 and $2 both being null seem irrelevant.

    – WinEunuuchs2Unix
    Dec 25 '16 at 2:18











  • @WinEunuuchs2Unix Not necessarily irrelevant - in some cases you want to ensure there's actually something instead of blank or null string in arguments. $1 could be unset or set to null string by user of the script. Consider this sequence of command: $ set '' bar then echo "x${1}x"; Both variables are set, but one of them is null.

    – Sergiy Kolodyazhnyy
    Dec 3 '18 at 5:54














35












35








35


15






I am running some script which passing the string argument and I want to do if else statement shown as below:



if [ $1 != '' ] && [ $2 != '' ]
then
do something.....


but it shown Error too many argument. Why?










share|improve this question
















I am running some script which passing the string argument and I want to do if else statement shown as below:



if [ $1 != '' ] && [ $2 != '' ]
then
do something.....


but it shown Error too many argument. Why?







command-line bash scripts






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 15 '15 at 22:42









Sylvain Pineau

48.8k16107150




48.8k16107150










asked Apr 6 '14 at 16:31









taymindis Woontaymindis Woon

4785916




4785916













  • You should provide 1. the command which you call the script and 2. the full output.

    – Lucio
    Apr 7 '14 at 3:46






  • 2





    You should use [[ ]]. Otherwise you have to quote your variables.

    – Christophe De Troyer
    Jan 8 '15 at 22:48











  • If $1 didn't exist then $2 would become $1 which makes the test of $1 and $2 both being null seem irrelevant.

    – WinEunuuchs2Unix
    Dec 25 '16 at 2:18











  • @WinEunuuchs2Unix Not necessarily irrelevant - in some cases you want to ensure there's actually something instead of blank or null string in arguments. $1 could be unset or set to null string by user of the script. Consider this sequence of command: $ set '' bar then echo "x${1}x"; Both variables are set, but one of them is null.

    – Sergiy Kolodyazhnyy
    Dec 3 '18 at 5:54



















  • You should provide 1. the command which you call the script and 2. the full output.

    – Lucio
    Apr 7 '14 at 3:46






  • 2





    You should use [[ ]]. Otherwise you have to quote your variables.

    – Christophe De Troyer
    Jan 8 '15 at 22:48











  • If $1 didn't exist then $2 would become $1 which makes the test of $1 and $2 both being null seem irrelevant.

    – WinEunuuchs2Unix
    Dec 25 '16 at 2:18











  • @WinEunuuchs2Unix Not necessarily irrelevant - in some cases you want to ensure there's actually something instead of blank or null string in arguments. $1 could be unset or set to null string by user of the script. Consider this sequence of command: $ set '' bar then echo "x${1}x"; Both variables are set, but one of them is null.

    – Sergiy Kolodyazhnyy
    Dec 3 '18 at 5:54

















You should provide 1. the command which you call the script and 2. the full output.

– Lucio
Apr 7 '14 at 3:46





You should provide 1. the command which you call the script and 2. the full output.

– Lucio
Apr 7 '14 at 3:46




2




2





You should use [[ ]]. Otherwise you have to quote your variables.

– Christophe De Troyer
Jan 8 '15 at 22:48





You should use [[ ]]. Otherwise you have to quote your variables.

– Christophe De Troyer
Jan 8 '15 at 22:48













If $1 didn't exist then $2 would become $1 which makes the test of $1 and $2 both being null seem irrelevant.

– WinEunuuchs2Unix
Dec 25 '16 at 2:18





If $1 didn't exist then $2 would become $1 which makes the test of $1 and $2 both being null seem irrelevant.

– WinEunuuchs2Unix
Dec 25 '16 at 2:18













@WinEunuuchs2Unix Not necessarily irrelevant - in some cases you want to ensure there's actually something instead of blank or null string in arguments. $1 could be unset or set to null string by user of the script. Consider this sequence of command: $ set '' bar then echo "x${1}x"; Both variables are set, but one of them is null.

– Sergiy Kolodyazhnyy
Dec 3 '18 at 5:54





@WinEunuuchs2Unix Not necessarily irrelevant - in some cases you want to ensure there's actually something instead of blank or null string in arguments. $1 could be unset or set to null string by user of the script. Consider this sequence of command: $ set '' bar then echo "x${1}x"; Both variables are set, but one of them is null.

– Sergiy Kolodyazhnyy
Dec 3 '18 at 5:54










5 Answers
5






active

oldest

votes


















48














Try using the -z test:



if [ -z "$1" ] && [ -z "$2" ]


From man bash:



-z string
True if the length of string is zero.





share|improve this answer


























  • It works for me!

    – pengisgood
    Jul 10 '17 at 8:03











  • it is interesting that the most voted and accepted answer does not actually answer the question asked.

    – mehmet
    Dec 2 '18 at 23:55











  • When writing portable shell scripts, this flag should be used with care, since on certain commercial Unixes this flag is faulty. See my answer for linked sources.

    – Sergiy Kolodyazhnyy
    Dec 3 '18 at 5:50



















11














Since this is tagged bash, I recommend that one use the extended test construct ([[...]]), and forget the quotes:



if [[ -z $1 && -z $2 ]]; then
...


Unless you are going for sh/POSIX compatibility, there is no reason not to use [[ ]].






share|improve this answer































    3














    The following also works,



    if [ "$1" == "" && "$2" == ""]; then
    echo NULL
    fi





    share|improve this answer


























    • The && and other logical command separators are not allowed in the classic test. You have to use other test constructs instead (like -a, I think)

      – muru
      Sep 21 '14 at 13:41



















    2














    For old version of the answer, see second portion of this answer. If you want to know about details, read on



    The cause of issue



    In the question itself, it is reported that OP sees too many arguments error, which when tested in bash doesn't seem to be the case:



    $ [ $1 != '' ] && [ $2 != '' ]
    bash: [: !=: unary operator expected


    With /bin/sh which is actually symlinked to /bin/dash on Ubuntu, error reported as follows:



    $ sh
    $ [ $1 != '' ] && [ $2 != '' ]
    sh: 1: [: !=: unexpected operator


    And the standalone /bin/test also :



    $ /usr/bin/test $1 != ''  
    /usr/bin/test: missing argument after ‘’


    Sidenote: If you're wondering what is /usr/bin/test and why I'm using bash and sh, then you should know that [ is alias for test command, which also exists as standalone executable or more commonly - as shell built-in which is what each shell will use first. As for if statements, they operate on exit statues of commands, hence why [ and test are commands, with everything else being arguments to that commands - improper order of those command-line args leads to errors.



    Back to the topic: it's unclear how OP got the unrelated error. However, in all 3 cases the issue is the same - unset variable will be treated as empty, thus what the shell sees with these unquoted variables is



    [ != '' ]


    which breaks syntax which test understands. Remember what I said about improper order of command-line arguments ? Hence why quoting is important. Let's enable diagnostic output and see what shell executes:



    $ set -x
    # throws error
    $ [ $1 != '' ] && [ $2 != '' ]
    + '[' '!=' '' ']'
    bash: [: !=: unary operator expected
    # no error
    $ [ "$1" != '' ] && [ "$2" != '' ] || echo null vars
    + '[' '' '!=' '' ']'
    + echo null vars
    null vars




    Better way to test unset variables



    A very frequent approach that you see around is this:



     if [ "x$var1" == "x"  ] && [ "x$var2" == "x"  ];                                                                
    then
    echo "both variables are null"
    fi


    To quote Gilles:




    In [ "x$1" = x"" ], the x prefix ensures that x"$1" cannot possibly look like an operator, and so the only way the shell can parse this test is by treating = as a binary operator.




    Presumably, this should be fairly portable since I've seen these in /bin/sh scripts. It also can be combined as in



    if [ "x${var1}${var2}" == "x" ]; then
    ...
    fi


    Of course we could use -z flag, however according to research in some shells, particularly ksh88 (according to Stephane Chazelas), this flag is faulty.



    See also




    • Performance of test command in various shell

    • Bash operators [ vs [[ vs ((






    share|improve this answer


























    • +1 for a very interesting approach.

      – WinEunuuchs2Unix
      Dec 3 '18 at 4:27











    • @WinEunuuchs2Unix Edited to make it even more interesting :)

      – Sergiy Kolodyazhnyy
      Dec 3 '18 at 4:48



















    0














    I think the title of the post is not accurate, as the intention in the message was to check if $1 and $2 are not null.
    The given example was just missing double quotes in $1 and $2 to work.
    Variables must be double quoted to be expanded when comparing strings.
    But, to check if $1 and $2 exist is the same as check if $2 exist, as it can't exist if $1 doesn't.
    The 'if' command is also not needed in this case, as 'test' returns true/false and uses '&&' as 'then' if return is 0/true:



    [ "$2" != '' ] && commands...


    Simpler, with -n (nonzero):



    [ -n "$2" ] && commands...


    To "check if $1 and $2 are null" would be the same as check if there is no parameter:



    [ $# -eq 0 ] && commands...





    share|improve this answer























      Your Answer








      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "89"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f444082%2fhow-to-check-if-1-and-2-are-null%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      48














      Try using the -z test:



      if [ -z "$1" ] && [ -z "$2" ]


      From man bash:



      -z string
      True if the length of string is zero.





      share|improve this answer


























      • It works for me!

        – pengisgood
        Jul 10 '17 at 8:03











      • it is interesting that the most voted and accepted answer does not actually answer the question asked.

        – mehmet
        Dec 2 '18 at 23:55











      • When writing portable shell scripts, this flag should be used with care, since on certain commercial Unixes this flag is faulty. See my answer for linked sources.

        – Sergiy Kolodyazhnyy
        Dec 3 '18 at 5:50
















      48














      Try using the -z test:



      if [ -z "$1" ] && [ -z "$2" ]


      From man bash:



      -z string
      True if the length of string is zero.





      share|improve this answer


























      • It works for me!

        – pengisgood
        Jul 10 '17 at 8:03











      • it is interesting that the most voted and accepted answer does not actually answer the question asked.

        – mehmet
        Dec 2 '18 at 23:55











      • When writing portable shell scripts, this flag should be used with care, since on certain commercial Unixes this flag is faulty. See my answer for linked sources.

        – Sergiy Kolodyazhnyy
        Dec 3 '18 at 5:50














      48












      48








      48







      Try using the -z test:



      if [ -z "$1" ] && [ -z "$2" ]


      From man bash:



      -z string
      True if the length of string is zero.





      share|improve this answer















      Try using the -z test:



      if [ -z "$1" ] && [ -z "$2" ]


      From man bash:



      -z string
      True if the length of string is zero.






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jul 16 '15 at 5:10









      A.B.

      68.5k12168258




      68.5k12168258










      answered Apr 6 '14 at 16:47









      Sylvain PineauSylvain Pineau

      48.8k16107150




      48.8k16107150













      • It works for me!

        – pengisgood
        Jul 10 '17 at 8:03











      • it is interesting that the most voted and accepted answer does not actually answer the question asked.

        – mehmet
        Dec 2 '18 at 23:55











      • When writing portable shell scripts, this flag should be used with care, since on certain commercial Unixes this flag is faulty. See my answer for linked sources.

        – Sergiy Kolodyazhnyy
        Dec 3 '18 at 5:50



















      • It works for me!

        – pengisgood
        Jul 10 '17 at 8:03











      • it is interesting that the most voted and accepted answer does not actually answer the question asked.

        – mehmet
        Dec 2 '18 at 23:55











      • When writing portable shell scripts, this flag should be used with care, since on certain commercial Unixes this flag is faulty. See my answer for linked sources.

        – Sergiy Kolodyazhnyy
        Dec 3 '18 at 5:50

















      It works for me!

      – pengisgood
      Jul 10 '17 at 8:03





      It works for me!

      – pengisgood
      Jul 10 '17 at 8:03













      it is interesting that the most voted and accepted answer does not actually answer the question asked.

      – mehmet
      Dec 2 '18 at 23:55





      it is interesting that the most voted and accepted answer does not actually answer the question asked.

      – mehmet
      Dec 2 '18 at 23:55













      When writing portable shell scripts, this flag should be used with care, since on certain commercial Unixes this flag is faulty. See my answer for linked sources.

      – Sergiy Kolodyazhnyy
      Dec 3 '18 at 5:50





      When writing portable shell scripts, this flag should be used with care, since on certain commercial Unixes this flag is faulty. See my answer for linked sources.

      – Sergiy Kolodyazhnyy
      Dec 3 '18 at 5:50













      11














      Since this is tagged bash, I recommend that one use the extended test construct ([[...]]), and forget the quotes:



      if [[ -z $1 && -z $2 ]]; then
      ...


      Unless you are going for sh/POSIX compatibility, there is no reason not to use [[ ]].






      share|improve this answer




























        11














        Since this is tagged bash, I recommend that one use the extended test construct ([[...]]), and forget the quotes:



        if [[ -z $1 && -z $2 ]]; then
        ...


        Unless you are going for sh/POSIX compatibility, there is no reason not to use [[ ]].






        share|improve this answer


























          11












          11








          11







          Since this is tagged bash, I recommend that one use the extended test construct ([[...]]), and forget the quotes:



          if [[ -z $1 && -z $2 ]]; then
          ...


          Unless you are going for sh/POSIX compatibility, there is no reason not to use [[ ]].






          share|improve this answer













          Since this is tagged bash, I recommend that one use the extended test construct ([[...]]), and forget the quotes:



          if [[ -z $1 && -z $2 ]]; then
          ...


          Unless you are going for sh/POSIX compatibility, there is no reason not to use [[ ]].







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Sep 21 '14 at 13:38









          murumuru

          1




          1























              3














              The following also works,



              if [ "$1" == "" && "$2" == ""]; then
              echo NULL
              fi





              share|improve this answer


























              • The && and other logical command separators are not allowed in the classic test. You have to use other test constructs instead (like -a, I think)

                – muru
                Sep 21 '14 at 13:41
















              3














              The following also works,



              if [ "$1" == "" && "$2" == ""]; then
              echo NULL
              fi





              share|improve this answer


























              • The && and other logical command separators are not allowed in the classic test. You have to use other test constructs instead (like -a, I think)

                – muru
                Sep 21 '14 at 13:41














              3












              3








              3







              The following also works,



              if [ "$1" == "" && "$2" == ""]; then
              echo NULL
              fi





              share|improve this answer















              The following also works,



              if [ "$1" == "" && "$2" == ""]; then
              echo NULL
              fi






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 3 '18 at 2:56









              Community

              1




              1










              answered Apr 6 '14 at 16:56









              Avinash RajAvinash Raj

              51.7k41167216




              51.7k41167216













              • The && and other logical command separators are not allowed in the classic test. You have to use other test constructs instead (like -a, I think)

                – muru
                Sep 21 '14 at 13:41



















              • The && and other logical command separators are not allowed in the classic test. You have to use other test constructs instead (like -a, I think)

                – muru
                Sep 21 '14 at 13:41

















              The && and other logical command separators are not allowed in the classic test. You have to use other test constructs instead (like -a, I think)

              – muru
              Sep 21 '14 at 13:41





              The && and other logical command separators are not allowed in the classic test. You have to use other test constructs instead (like -a, I think)

              – muru
              Sep 21 '14 at 13:41











              2














              For old version of the answer, see second portion of this answer. If you want to know about details, read on



              The cause of issue



              In the question itself, it is reported that OP sees too many arguments error, which when tested in bash doesn't seem to be the case:



              $ [ $1 != '' ] && [ $2 != '' ]
              bash: [: !=: unary operator expected


              With /bin/sh which is actually symlinked to /bin/dash on Ubuntu, error reported as follows:



              $ sh
              $ [ $1 != '' ] && [ $2 != '' ]
              sh: 1: [: !=: unexpected operator


              And the standalone /bin/test also :



              $ /usr/bin/test $1 != ''  
              /usr/bin/test: missing argument after ‘’


              Sidenote: If you're wondering what is /usr/bin/test and why I'm using bash and sh, then you should know that [ is alias for test command, which also exists as standalone executable or more commonly - as shell built-in which is what each shell will use first. As for if statements, they operate on exit statues of commands, hence why [ and test are commands, with everything else being arguments to that commands - improper order of those command-line args leads to errors.



              Back to the topic: it's unclear how OP got the unrelated error. However, in all 3 cases the issue is the same - unset variable will be treated as empty, thus what the shell sees with these unquoted variables is



              [ != '' ]


              which breaks syntax which test understands. Remember what I said about improper order of command-line arguments ? Hence why quoting is important. Let's enable diagnostic output and see what shell executes:



              $ set -x
              # throws error
              $ [ $1 != '' ] && [ $2 != '' ]
              + '[' '!=' '' ']'
              bash: [: !=: unary operator expected
              # no error
              $ [ "$1" != '' ] && [ "$2" != '' ] || echo null vars
              + '[' '' '!=' '' ']'
              + echo null vars
              null vars




              Better way to test unset variables



              A very frequent approach that you see around is this:



               if [ "x$var1" == "x"  ] && [ "x$var2" == "x"  ];                                                                
              then
              echo "both variables are null"
              fi


              To quote Gilles:




              In [ "x$1" = x"" ], the x prefix ensures that x"$1" cannot possibly look like an operator, and so the only way the shell can parse this test is by treating = as a binary operator.




              Presumably, this should be fairly portable since I've seen these in /bin/sh scripts. It also can be combined as in



              if [ "x${var1}${var2}" == "x" ]; then
              ...
              fi


              Of course we could use -z flag, however according to research in some shells, particularly ksh88 (according to Stephane Chazelas), this flag is faulty.



              See also




              • Performance of test command in various shell

              • Bash operators [ vs [[ vs ((






              share|improve this answer


























              • +1 for a very interesting approach.

                – WinEunuuchs2Unix
                Dec 3 '18 at 4:27











              • @WinEunuuchs2Unix Edited to make it even more interesting :)

                – Sergiy Kolodyazhnyy
                Dec 3 '18 at 4:48
















              2














              For old version of the answer, see second portion of this answer. If you want to know about details, read on



              The cause of issue



              In the question itself, it is reported that OP sees too many arguments error, which when tested in bash doesn't seem to be the case:



              $ [ $1 != '' ] && [ $2 != '' ]
              bash: [: !=: unary operator expected


              With /bin/sh which is actually symlinked to /bin/dash on Ubuntu, error reported as follows:



              $ sh
              $ [ $1 != '' ] && [ $2 != '' ]
              sh: 1: [: !=: unexpected operator


              And the standalone /bin/test also :



              $ /usr/bin/test $1 != ''  
              /usr/bin/test: missing argument after ‘’


              Sidenote: If you're wondering what is /usr/bin/test and why I'm using bash and sh, then you should know that [ is alias for test command, which also exists as standalone executable or more commonly - as shell built-in which is what each shell will use first. As for if statements, they operate on exit statues of commands, hence why [ and test are commands, with everything else being arguments to that commands - improper order of those command-line args leads to errors.



              Back to the topic: it's unclear how OP got the unrelated error. However, in all 3 cases the issue is the same - unset variable will be treated as empty, thus what the shell sees with these unquoted variables is



              [ != '' ]


              which breaks syntax which test understands. Remember what I said about improper order of command-line arguments ? Hence why quoting is important. Let's enable diagnostic output and see what shell executes:



              $ set -x
              # throws error
              $ [ $1 != '' ] && [ $2 != '' ]
              + '[' '!=' '' ']'
              bash: [: !=: unary operator expected
              # no error
              $ [ "$1" != '' ] && [ "$2" != '' ] || echo null vars
              + '[' '' '!=' '' ']'
              + echo null vars
              null vars




              Better way to test unset variables



              A very frequent approach that you see around is this:



               if [ "x$var1" == "x"  ] && [ "x$var2" == "x"  ];                                                                
              then
              echo "both variables are null"
              fi


              To quote Gilles:




              In [ "x$1" = x"" ], the x prefix ensures that x"$1" cannot possibly look like an operator, and so the only way the shell can parse this test is by treating = as a binary operator.




              Presumably, this should be fairly portable since I've seen these in /bin/sh scripts. It also can be combined as in



              if [ "x${var1}${var2}" == "x" ]; then
              ...
              fi


              Of course we could use -z flag, however according to research in some shells, particularly ksh88 (according to Stephane Chazelas), this flag is faulty.



              See also




              • Performance of test command in various shell

              • Bash operators [ vs [[ vs ((






              share|improve this answer


























              • +1 for a very interesting approach.

                – WinEunuuchs2Unix
                Dec 3 '18 at 4:27











              • @WinEunuuchs2Unix Edited to make it even more interesting :)

                – Sergiy Kolodyazhnyy
                Dec 3 '18 at 4:48














              2












              2








              2







              For old version of the answer, see second portion of this answer. If you want to know about details, read on



              The cause of issue



              In the question itself, it is reported that OP sees too many arguments error, which when tested in bash doesn't seem to be the case:



              $ [ $1 != '' ] && [ $2 != '' ]
              bash: [: !=: unary operator expected


              With /bin/sh which is actually symlinked to /bin/dash on Ubuntu, error reported as follows:



              $ sh
              $ [ $1 != '' ] && [ $2 != '' ]
              sh: 1: [: !=: unexpected operator


              And the standalone /bin/test also :



              $ /usr/bin/test $1 != ''  
              /usr/bin/test: missing argument after ‘’


              Sidenote: If you're wondering what is /usr/bin/test and why I'm using bash and sh, then you should know that [ is alias for test command, which also exists as standalone executable or more commonly - as shell built-in which is what each shell will use first. As for if statements, they operate on exit statues of commands, hence why [ and test are commands, with everything else being arguments to that commands - improper order of those command-line args leads to errors.



              Back to the topic: it's unclear how OP got the unrelated error. However, in all 3 cases the issue is the same - unset variable will be treated as empty, thus what the shell sees with these unquoted variables is



              [ != '' ]


              which breaks syntax which test understands. Remember what I said about improper order of command-line arguments ? Hence why quoting is important. Let's enable diagnostic output and see what shell executes:



              $ set -x
              # throws error
              $ [ $1 != '' ] && [ $2 != '' ]
              + '[' '!=' '' ']'
              bash: [: !=: unary operator expected
              # no error
              $ [ "$1" != '' ] && [ "$2" != '' ] || echo null vars
              + '[' '' '!=' '' ']'
              + echo null vars
              null vars




              Better way to test unset variables



              A very frequent approach that you see around is this:



               if [ "x$var1" == "x"  ] && [ "x$var2" == "x"  ];                                                                
              then
              echo "both variables are null"
              fi


              To quote Gilles:




              In [ "x$1" = x"" ], the x prefix ensures that x"$1" cannot possibly look like an operator, and so the only way the shell can parse this test is by treating = as a binary operator.




              Presumably, this should be fairly portable since I've seen these in /bin/sh scripts. It also can be combined as in



              if [ "x${var1}${var2}" == "x" ]; then
              ...
              fi


              Of course we could use -z flag, however according to research in some shells, particularly ksh88 (according to Stephane Chazelas), this flag is faulty.



              See also




              • Performance of test command in various shell

              • Bash operators [ vs [[ vs ((






              share|improve this answer















              For old version of the answer, see second portion of this answer. If you want to know about details, read on



              The cause of issue



              In the question itself, it is reported that OP sees too many arguments error, which when tested in bash doesn't seem to be the case:



              $ [ $1 != '' ] && [ $2 != '' ]
              bash: [: !=: unary operator expected


              With /bin/sh which is actually symlinked to /bin/dash on Ubuntu, error reported as follows:



              $ sh
              $ [ $1 != '' ] && [ $2 != '' ]
              sh: 1: [: !=: unexpected operator


              And the standalone /bin/test also :



              $ /usr/bin/test $1 != ''  
              /usr/bin/test: missing argument after ‘’


              Sidenote: If you're wondering what is /usr/bin/test and why I'm using bash and sh, then you should know that [ is alias for test command, which also exists as standalone executable or more commonly - as shell built-in which is what each shell will use first. As for if statements, they operate on exit statues of commands, hence why [ and test are commands, with everything else being arguments to that commands - improper order of those command-line args leads to errors.



              Back to the topic: it's unclear how OP got the unrelated error. However, in all 3 cases the issue is the same - unset variable will be treated as empty, thus what the shell sees with these unquoted variables is



              [ != '' ]


              which breaks syntax which test understands. Remember what I said about improper order of command-line arguments ? Hence why quoting is important. Let's enable diagnostic output and see what shell executes:



              $ set -x
              # throws error
              $ [ $1 != '' ] && [ $2 != '' ]
              + '[' '!=' '' ']'
              bash: [: !=: unary operator expected
              # no error
              $ [ "$1" != '' ] && [ "$2" != '' ] || echo null vars
              + '[' '' '!=' '' ']'
              + echo null vars
              null vars




              Better way to test unset variables



              A very frequent approach that you see around is this:



               if [ "x$var1" == "x"  ] && [ "x$var2" == "x"  ];                                                                
              then
              echo "both variables are null"
              fi


              To quote Gilles:




              In [ "x$1" = x"" ], the x prefix ensures that x"$1" cannot possibly look like an operator, and so the only way the shell can parse this test is by treating = as a binary operator.




              Presumably, this should be fairly portable since I've seen these in /bin/sh scripts. It also can be combined as in



              if [ "x${var1}${var2}" == "x" ]; then
              ...
              fi


              Of course we could use -z flag, however according to research in some shells, particularly ksh88 (according to Stephane Chazelas), this flag is faulty.



              See also




              • Performance of test command in various shell

              • Bash operators [ vs [[ vs ((







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 3 '18 at 5:47

























              answered Dec 24 '16 at 23:49









              Sergiy KolodyazhnyySergiy Kolodyazhnyy

              71.6k9147313




              71.6k9147313













              • +1 for a very interesting approach.

                – WinEunuuchs2Unix
                Dec 3 '18 at 4:27











              • @WinEunuuchs2Unix Edited to make it even more interesting :)

                – Sergiy Kolodyazhnyy
                Dec 3 '18 at 4:48



















              • +1 for a very interesting approach.

                – WinEunuuchs2Unix
                Dec 3 '18 at 4:27











              • @WinEunuuchs2Unix Edited to make it even more interesting :)

                – Sergiy Kolodyazhnyy
                Dec 3 '18 at 4:48

















              +1 for a very interesting approach.

              – WinEunuuchs2Unix
              Dec 3 '18 at 4:27





              +1 for a very interesting approach.

              – WinEunuuchs2Unix
              Dec 3 '18 at 4:27













              @WinEunuuchs2Unix Edited to make it even more interesting :)

              – Sergiy Kolodyazhnyy
              Dec 3 '18 at 4:48





              @WinEunuuchs2Unix Edited to make it even more interesting :)

              – Sergiy Kolodyazhnyy
              Dec 3 '18 at 4:48











              0














              I think the title of the post is not accurate, as the intention in the message was to check if $1 and $2 are not null.
              The given example was just missing double quotes in $1 and $2 to work.
              Variables must be double quoted to be expanded when comparing strings.
              But, to check if $1 and $2 exist is the same as check if $2 exist, as it can't exist if $1 doesn't.
              The 'if' command is also not needed in this case, as 'test' returns true/false and uses '&&' as 'then' if return is 0/true:



              [ "$2" != '' ] && commands...


              Simpler, with -n (nonzero):



              [ -n "$2" ] && commands...


              To "check if $1 and $2 are null" would be the same as check if there is no parameter:



              [ $# -eq 0 ] && commands...





              share|improve this answer




























                0














                I think the title of the post is not accurate, as the intention in the message was to check if $1 and $2 are not null.
                The given example was just missing double quotes in $1 and $2 to work.
                Variables must be double quoted to be expanded when comparing strings.
                But, to check if $1 and $2 exist is the same as check if $2 exist, as it can't exist if $1 doesn't.
                The 'if' command is also not needed in this case, as 'test' returns true/false and uses '&&' as 'then' if return is 0/true:



                [ "$2" != '' ] && commands...


                Simpler, with -n (nonzero):



                [ -n "$2" ] && commands...


                To "check if $1 and $2 are null" would be the same as check if there is no parameter:



                [ $# -eq 0 ] && commands...





                share|improve this answer


























                  0












                  0








                  0







                  I think the title of the post is not accurate, as the intention in the message was to check if $1 and $2 are not null.
                  The given example was just missing double quotes in $1 and $2 to work.
                  Variables must be double quoted to be expanded when comparing strings.
                  But, to check if $1 and $2 exist is the same as check if $2 exist, as it can't exist if $1 doesn't.
                  The 'if' command is also not needed in this case, as 'test' returns true/false and uses '&&' as 'then' if return is 0/true:



                  [ "$2" != '' ] && commands...


                  Simpler, with -n (nonzero):



                  [ -n "$2" ] && commands...


                  To "check if $1 and $2 are null" would be the same as check if there is no parameter:



                  [ $# -eq 0 ] && commands...





                  share|improve this answer













                  I think the title of the post is not accurate, as the intention in the message was to check if $1 and $2 are not null.
                  The given example was just missing double quotes in $1 and $2 to work.
                  Variables must be double quoted to be expanded when comparing strings.
                  But, to check if $1 and $2 exist is the same as check if $2 exist, as it can't exist if $1 doesn't.
                  The 'if' command is also not needed in this case, as 'test' returns true/false and uses '&&' as 'then' if return is 0/true:



                  [ "$2" != '' ] && commands...


                  Simpler, with -n (nonzero):



                  [ -n "$2" ] && commands...


                  To "check if $1 and $2 are null" would be the same as check if there is no parameter:



                  [ $# -eq 0 ] && commands...






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 13 at 6:49









                  Guariba SomGuariba Som

                  11




                  11






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Ask Ubuntu!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f444082%2fhow-to-check-if-1-and-2-are-null%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Human spaceflight

                      Can not write log (Is /dev/pts mounted?) - openpty in Ubuntu-on-Windows?

                      File:DeusFollowingSea.jpg