Reputation: 11
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
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
Reputation: 389
I see two mistakes:
This is a short example:
#!/bin/bash
files=`ls`
for file in $files
do
echo "file: $file"
done
Upvotes: 0
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