user2829366
user2829366

Reputation: 11

bash backup script error

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?

Upvotes: 0

Views: 272

Answers (3)

el_tenedor
el_tenedor

Reputation: 664

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`

Upvotes: 0

HapKoM
HapKoM

Reputation: 389

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

Upvotes: 0

Kent
Kent

Reputation: 195039

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)

Upvotes: 3

Related Questions