I'm new to shell scripting and I trying to write a script that:

  • Prompts for a directory
  • Loops through the directory
  • If it find files it then backs them up using a function in the script
  • Creates a backup

I just created a file called file.bak for all the files to be copied into if they were found.


function backup()
cp"$name" >> file.bak

#Main Script
echo -n "Please enter a directory name: "
read name
if [ -O "$name" ] || [ -G "$name" ]
echo "$name has no files."
  • For meaningful answers, you might want to explain what you mean by "create a backup"; do you want to copy each file to a new file, or to create a single file containing the concatenation of your source files? – dhag Nov 30 '15 at 16:36
  • Copy each file to a new file which is file.bak – user144380 Nov 30 '15 at 16:41
  • So there is only one output file name. What if the directory contains more than one file? – dhag Nov 30 '15 at 16:43
  • Perhaps it would be best if you showed us an expected list of files before backing up, and after backing up. – dhag Nov 30 '15 at 16:44
  • Write a script (called backupfile.sh) that consists two parts: A function called backup that has parameter, the name of the file to backup A main section, which prompts users to enter a directory, and then loop through the items in the directory. If it is a file, it calls the backup function to create a backup copy of the file. – user144380 Nov 30 '15 at 16:48

For starters, this probably doesn't do what you mean to do:

cp"$name" >> file.bak

This will attempt to call a command whose first two characters are cp, and the rest are the value of $name. Such a command probably doesn't exist.

Adding a space doesn't solve the problem:

cp "$name" >> file.bak

This will call the command cp with a single parameter (which is an invalid way to call it), and append whatever this command prints on stdout into a file named file.bak. You probably want something like cp "$name" file.bak or perhaps cat "$name" >> file.bak

The tests using -O and -G don't make a lot of sense either; the error message you are printing does not really match what those operators check for.


You could try something like


echo -n "Please enter a directory name: "
read name
find $name -type f -exec cp {} {}.bak \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy