0

I'm new to Bash scripts, trying to make my first backup script. When I run it I always get something like this:

./backupscript.sh: line 9: [3=1: command not found
./backupscript.sh: line 9: 3=2]: command not found
./backupscript.sh: line 15: [3=1: command not found
./backupscript.sh: line 15: 3=3]: command not found

I have tried many different syntax, like ["var"="1"]||["var"=2], double brackets, without quotes, ()-brackets single and double and I'm losing my mind. It seems like bash isn't recognising at all that it's an if-statement. What's wrong? Thanks!

#!/bin/bash

cd /
NOW=$(date +"%m_%d_%Y")
echo "Please input: 1=full 2=system 3=home"
read choice

if  ["$choice"="1" || "$choice"="2"]; then
echo "--- STARTING SYSTEMBACKUP ---"
tar -cvpzf systembackup_$NOW.tar.gz --exclude=/proc --exclude=/lost+found --exclude=/systembackup.tar.gz --exclude=/mnt --exclude=/sys --exclude=/dev --exclude=/run --exclude=/media --exclude=/home /
echo "--- SYSTEM BACKUP DONE ---"
fi

if  ["$choice"="1" || "$choice"="3"]; then
echo "--- STARTING HOMEBACKUP (excluding ~/Seafile) ---"
tar -cvpzf homebackup_$NOW.tar.gz --exclude=/home/matias/Seafile /home
echo "--- HOMEBACKUP DONE ---"
fi

EDIT: Proper syntax suggested here did the trick, thanks everyone! I'm still looking for good guides on Bash :)

Matuardo
  • 17
  • 2

2 Answers2

0

Use the following as a best practice:

if  [[ $choice == 1 || $choice == 2 ]]; then
    ...
fi

Notice the spaces and the == for equality test.

|| and && work in double brackets. Also has some other nice features, like REGEX matching with =~ along with operators like they are known in C-like languages along with less surprises.

Farhad Farahi
  • 35,528
  • 7
  • 73
  • 70
0

As @fedorqui said, you need spaces around the brackets. That is because [ is actually a synonym for test, a real program, and so is the name of an actual command.

To make your life easier in the future, use spaces and double brackets instead ([[ and ]]). Those are handled internally by bash and are more robust against accidental errors such as forgetting the quotes around a variable substitution. Plus, && and || work as logical AND and OR in double-brackets, but not in single brackets - you have to use -a and -o instead in [ ] expressions.

Using double-brackets ("conditional expressions" in bash), you can write:

if [[ $choice = 1 || $ choice = 3 ]]; then
    ...
fi

and get the result you expect.

cxw
  • 16,685
  • 2
  • 45
  • 81
  • 1
    Note that `-a` and `-o` are considered obsolete and should not be used in new code. Use `[ ... ] && [ ... ]` and `[ ... ] || [ ... ]` (i.e., two separate `[` commands) instead. – chepner Dec 16 '16 at 15:00
  • @chepner Didn't know that! Would you please give me a link to the details? Thanks! – cxw Dec 16 '16 at 15:05