0

So I'm writing a simple backup script that when called will either back up a specific file or all the files in my current directory into my backup directory. This is my script

#!/bin/bash

#verify if $1 is empty, if so, copy all content to backup directory

if [ -z "$1" ]
then

    $files=ls
    #Looping through files
    for file in $files
    do
        cp $file ../backup/
    done      
 #else copy files specified 

else

$files=ls $1

    #Looping through files 
    for file in $files
    do
        cp $file ../backup/
    done
fi

and the only error I'm getting is:

./backup: line 7: =ls: command not found

I'm not sure why the script won't recognize ls as a command. Any ideas?

3 Answers 3

3

to assign a variable, you don't need the dollar sign:

files=foo

to save the output of an command to a var, you need do:

files=$(ls)

or

files=$(ls /path/to/some/dir)
Sign up to request clarification or add additional context in comments.

Comments

0

I see two mistakes:

  1. When you initialize variable "files" you should not prepend it with "$" symbol
  2. Command ls should be placed in back quotes (`):

This is a short example:

#!/bin/bash

files=`ls`

for file in $files
do
    echo "file: $file"
done

Comments

0

You should try putting the ls into ` marks - better, the back quote. Like this:

files=`ls`

Here a little background. Check this page for more information about quotation marks in the shell environment:

The back quote is not used for quoting characters. That character is used for command substitution, where the characters between them are executed by the shell and the results is inserted on that line.

Example:

echo the date is `date`

Comments

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.