Bash: using a variables twice in a string


I’ve been playing with bash and created a script to create the template project structure and virtual environment for LPTHW.

It all works fine accept when I need to copy a file from a template location into the new file structure. I know the issue is syntax as it works when the variable is hard-coded, but I’ve tried a number of variations (based on similar Stack Overflow questions) and cannot get it right.

I capture the proposed project name into the variable below:


Then (after installation and creation of the file directory), this works:

cp ~/projects/templates/ ~/projects/"$project"/

But using the variable twice in the same string does not.

cp ~/projects/templates/ ~/projects/"$project"/tests/"$project"

Strangely, it recognises/substitutes the $ instance but leaves a blank at the first instance.

What is the correct syntax? I’ve tried wrapping the string in “”, and using () and {} with the parameter but can’t get it right.


Easy, just put the whole path in quotes:


I think you can also do this:


I forget if it’s ${} or $() but there’s a way to add extra armor. Also, at the top of your script add:

set -e

That will cause it to abort when there’s an error, instead of just running until the end and ignoring errors.


Tried (with project name refactor):

cp ~/projects/templates/ "~/projects/$project/tests/$"


cp: ~/projects/refactor/tests/.py: No such file or directory


 cp ~/projects/templates/ "~/projects/${project}/tests/${project}"

And still got:

cp: ~/projects/notworking/tests/ No such file or directory

This has managed the dual substitution, but hasn’t copied the file. Is this because I am trying to copy the file to an empty location. Should I just copy it to the folder, then rename?


Nope. I can’t crack this.

Anyone fancy a crack? Line 45 is the issue…


It looks like those directories don’t exist. Are you doing:

mkdir -p “~/projects/${project}/tests/”

First? If those dirs don’t exist then when you try to copy a file there it’ll fail.