Help with IF command.

Discussion in 'Getting Started' started by Malohhree, Jul 2, 2014.

  1. Malohhree

    Malohhree New Member

    Messages:
    3
    Likes Received:
    1
    Trophy Points:
    3
    I need to make a script that basically says (filename is truth) -

    if truth does not exist, then "cd /home/mallory ; ./truth", else ./truth


    Help? I know -e means does exist, but is there a command for does not exist?
  2. MikeyD

    MikeyD Active Member

    Messages:
    219
    Likes Received:
    105
    Trophy Points:
    43
    -f is generally used more because it is more common between different shells (true if string given is a file), but to get the opposite just use a bang (!) symbol.

    So if....

    Code:
    if [ -f "truth" ]; then
    echo "truth is a file"
    fi
    Then...

    Code:
    if [ ! -f "truth" ]; then
    echo "truth is not a file"
    fi
    Remember spacing matters! There must be spaces before and after the bang (!) and as always there must be spaces between your expression and the [ ] brackets.

    This is a good resource for the most common if/else condition flags (table at the bottom of the page):
    http://codewiki.wikidot.com/shell-script:if-else
  3. Malohhree

    Malohhree New Member

    Messages:
    3
    Likes Received:
    1
    Trophy Points:
    3
    So, is this correct? -

    alias truth='if ! -f truth, then "cd /home/mallory ; ./truth", else "./truth"'

    Tell me exactly what this script would do. What I'm aiming for is if the file isn't there, it will take you to the directory it is in and run it. If the file is there, it will run it.
  4. rstanley

    rstanley Member

    Messages:
    44
    Likes Received:
    33
    Trophy Points:
    18
    Instead of writing an alias for this, I would create a function, and place it in either .profile, or .bash_profile, depending on the Distro you are using. This code will do what you intended. Test it out!

    Your code could or should look like this:

    Code:
    function truth()
    {
        if [ ! -f "truth" ]; then
          cd /home/mallory ; ./truth
        else
          ./truth
        fi
    }
    
    Also, I would study the following two tutorials:

    I realize I may have just done your homework! ;^)

    Good luck!
    Last edited: Jul 3, 2014

Share This Page