Find the answer to your Linux question:
Results 1 to 2 of 2
Code: #/bin/bash if [ test "$1" -z = "0" ]; then echo "usage test noargs" exit 1 fi case $1 in one) echo "first argument";; *) echo $1;; esac Command ...
  1. #1
    Just Joined!
    Join Date
    Nov 2007
    Posts
    8

    Question scripting help

    Code:
    #/bin/bash
    if [ test "$1" -z = "0" ]; then
       echo "usage test noargs"
       exit 1
    fi
    
    case $1 in
     one) echo "first argument";;
     *) echo $1;;
    esac
    
    Command line:
    [root@localhost centos]# ./test
    ./test: line 2: [: too many arguments
    
    [root@localhost centos]#

  2. #2
    Linux Guru
    Join Date
    Nov 2007
    Location
    Córdoba (Spain)
    Posts
    1,513
    Quote Originally Posted by slyth View Post
    [CODE]
    #/bin/bash
    if [ test "$1" -z = "0" ]; then
    This is redundantly redundant First, you use either "if" or "test", second, you use -z or = "0", but not both.

    So, these are equivalent:

    Code:
    if [ -z "$foo" ]; then echo foo; fi
    if [ "$foo" == "" ]; then echo foo; fi
    test -z "$foo" && echo foo
    EDITED (for clarification).

    Note that -z and == "0" are not the same. -z is true if the string length is zero, but not if the string is equal to "0" (its length in that case would be 1 character). You could also use if [ "$#" == "0" ], since "$#" contains the number of parameters, this would be (semantically) more accurate for your purpose. However, measuring the length of the first parameter should work equally, unless someone is idiot enough to send a "" (empty string) as first parameter (and in that case, you would want the program to abort anyway).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...