Bash: using a variables twice in a string


#1

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:

$project

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

cp ~/projects/templates/setup.py ~/projects/"$project"/setup.py

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

cp ~/projects/templates/NAME_tests.py ~/projects/"$project"/tests/"$project"_tests.py

Strangely, it recognises/substitutes the $project_tests.py 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.


#2

Easy, just put the whole path in quotes:

“~/projects/$project/tests/$project_tests.py”

I think you can also do this:

“~/projects/${project}/tests/${project}_tests.py”

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.


#3

Tried (with project name refactor):

cp ~/projects/templates/NAME_tests.py "~/projects/$project/tests/$project_tests.py"

Got:

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

Tried:

 cp ~/projects/templates/NAME_tests.py "~/projects/${project}/tests/${project}_tests.py"

And still got:

cp: ~/projects/notworking/tests/notworking_tests.py: 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?


#4

Nope. I can’t crack this.

Anyone fancy a crack? Line 45 is the issue…


#5

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.