0

i am new to shell scripting, i am trying to backup a file "main.sh" to "main.sh.bak" using a shell script. If the file exists perform the copy, else display a message. below is the script i am trying, i need to help in the "if" condition to check if the file exists or not in the current directory.

#!/bin/bash

echo "enter the file name"
read FILE
if [ -f $FILE ]; then
    cp $FILE $FILE.bak
    echo "file successfully backed up"
else
    echo "file does not exists"
    exit 1
fi

exit 0
1

4 Answers 4

2

The test command ([ xxx ] is the same as test xxx) for an existing regular file looks like:

if [ -f $FILE ]; then
  <do something>
else
  <do something>
fi

Important note: -f is for regular files, that is, for instance, not symbolic links or directories. So, if your files can be something else than regular files, type man test to know more about all test options and adapt to your specific case.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the suggestion. could you help me with some articles / Websites from where i could learn / get practical examples of Shell scripts. Apparently, learning shell scripting and implementing it is what matters. Hence certain practical examples would be useful.
I frequently recommend this bash beginners' guide: tldp.org/LDP/Bash-Beginners-Guide/html/index.html. It is probably not the most up to date but I find it well written.
1

You can check if is a file exists with this sentence:

if [ -e $ FILE ] 

Usign condition with [ ] are the same than command test there are more options to checks files, for instance:

 -b FILE
          FILE exists and is block special
 -d FILE
          FILE exists and is a directory
 -f FILE
          FILE exists and is a regular file

And much more, please execute man test to see all options

Comments

0

There is also an error in your script. You are missing an semicolon after the if statement.

So

if [ $FILE ] then

Should become:

if [ $FILE ]; then

Comments

-1
echo -n "enter file name : "
read file
if [ -e $path/main.sh ]; then
cp /path/main.sh /path/main.bak
echo "Successfully back up"
else
echo "failed"
fi
exit 0;

1 Comment

Please add short explanation to your answer for future visitors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.