0

I'm writing a bash script to get the latest file from a directory for backup purposes. Here is the script:

#!/bin/sh

set -u
set -e

backup_dir=/media/backup

cd $backup_dir

tar_file= $(ls -Art | tail -n 1)

#ls -Art | tail -n 1

echo $tar_file

When I run the script it gets the right file but also returns a not found error and I don't know why:

./backup: 10: 20130403-120001.tar.gz: not found

I tested it with the line that's commented out, not putting it as a variable and that works without throwing an error so it should work.

2 Answers 2

3

Remove the space after the =:

tar_file=$(ls -Art | tail -n 1)

With the space, the line is interpreted as assigning nothing to $tar_file and running the command that is obtained as the output of the $(...). That command is not found.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow such a simple mistake, thanks for the explanation of what happens as well!
2

Is it correct to have

tar_file= $(ls -Art | tail -n 1)

and not

tar_file=$(ls -Art | tail -n 1)

?

(mind the space)

1 Comment

Thanks man, I'm going to mark choroba's answer as correct just because he gave an explanation of what the space does to the code, thanks all the same though!

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.