If statements in shell

Discussion in 'Mac Programming' started by lynkynpark86, Apr 11, 2012.

  1. macrumors 6502

    Joined:
    Mar 16, 2010
    Messages:
    330
    Location:
    Maine, USA, Earth, Solar System, Milky Way, Univer
    #1
    Does anyone know how I would do this in a shell script?
    If x is a file: somecommand
    If x is a directory: someothercommand
     
  2. macrumors 68030

    Joined:
    Feb 13, 2012
    Messages:
    2,660
    Location:
    Perth, Western Australia
    #2
    Which shell? sh? csh?

    edit:

    you could use "test".

    read

    man test
     
  3. dmi
    macrumors regular

    Joined:
    Dec 21, 2010
    Messages:
    100
    #3
    test -f x && somecommand
    test -d x && someothercommand
     
  4. macrumors 68040

    Joined:
    Feb 2, 2008
    Messages:
    3,360
    #4
    [ is an alias for test, which is quite funny I think. :D Try: man [ it will bring up the manual for test. It gives a bit more syntactically pleasing look if used in a script.

    Code:
    if [ -f $1 ]
    then
        echo file
    else if [ -d $1 ]
        echo directory
    fi
    
     
  5. macrumors 6502

    seepel

    Joined:
    Dec 22, 2009
    Messages:
    471
    #5
    this hits the nail on the head and for more detail see http://tldp.org/LDP/abs/html/fto.html
     
  6. macrumors 603

    Joined:
    Aug 9, 2009
    Messages:
    6,404
    #6
    Aha, it's: The Linux Documentation Project. Not: Too Long Didn't P*.

    FWIW, there are also the shell builtins [[ and ]], via 'man bash'. Somewhat different syntax for the expressions, but otherwise the same as test and [ (which are also bash builtins).
     
  7. dmi
    macrumors regular

    Joined:
    Dec 21, 2010
    Messages:
    100
    #7
    test and [ are /bin utilities, which would work in all shells
    [[ ... ]] is a bash (and ksh) built in
     
  8. macrumors 603

    Joined:
    Aug 9, 2009
    Messages:
    6,404
    #8
    FWIW, test and [ are bash builtins. They also exist as /bin tools, but bash (like other shells) searches its builtins first, unless the command contains a slash.

    Try this:
    Code:
    type [ test
    
    type is another builtin, otherwise similar to which (which isn't a builtin in bash).
     

Share This Page