Help with IF command.

M

Malohhree

Guest
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?
 


-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
 
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.
 
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.
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:
Ya, you have to write a function but they are more powerful and prefered.

Functions supersede aliases and you can't see your local aliases in a function but you can see other functions. Plus, you have a lot more power with them and they act just like aliases.

Put them in a script or in your ~/.bashrc file.
 

Members online


Top