1

I have the following script sample:

#!/bin/bash

# Aborts the script on "simple command failure" (does not cover pipes)
set -e

# Makes sure we do not run the script outside the correct directory (i.e. the backup directory)
projects_directory='~/projects' 
backup_drectory="${projects_directory}/backup/"
echo "Backup directory: ${backup_drectory}"

if [ ! -d "$projects_directory" ]; then 
    mkdir "$projects_directory"
    echo "${projects_directory} created successfully" 
fi

Which fails miserably with the following output:

Backup directory: ~/projects/backup/
mkdir: cannot create directory `~/projects': No such file or directory

I do not understand why. If I enter the mkdir ~/projects command manually in a Terminal, the directory gets created. Any suggestion is most welcome.

4
  • Try to replace the ~ with your absolute home directory (/home/username/). Which user executes your backup script (are you using a cron job?) Commented Sep 15, 2012 at 12:32
  • I am planning to use cron, yes. So far I am testing it manually via Terminal. Your solution works. Could you explain to me why ? Is ther any workaround so I do not have to hardcode the user path into the script ? Commented Sep 15, 2012 at 12:34
  • 2
    Shell quoting is your enemy. You can read about how the shell handles single versus double quotes here: mywiki.wooledge.org/Quotes. Commented Sep 15, 2012 at 12:35
  • 1
    the answer given by lanzz is correct. Make sure to start the script by the correct user (using crontab -e from the users shell) Commented Sep 15, 2012 at 12:35

1 Answer 1

7

Remove the single quotes:

projects_directory=~/projects

The quoting prevents the shell from expanding the ~ character.

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

3 Comments

Thanks ! Beginner's mistake ;)
+1. I also recommend using mkdir -p (make parent directories as needed).
Thanks x2! So I do not need to check for ~/projects existence, I can directly issue mkdir -p ~/projects/backup. You made my day sir !

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.