1

I need to insert variables into a string to create a URL. Right now, I'm looping over an array of values and inserting them into the string.

year="2015"
for i in "${array[@]}"
do
    url="https://www.my-website.com/place/PdfLinkServlet?file=\place\\$i\099%2Bno-display\\$year_$i.pdf"
    echo $url
done

The $i is being replaced with the corresponding array element, but $year just leaves a blank space. Can someone explain why and how to get a url that looks like: url="https://www.my-website.com/place/PdfLinkServlet?file=\place\place_id\099%2Bno-display\2015_place_id.pdf"

3 Answers 3

4

Because variable names can legally contain _ characters, there's no way for Bash to know that you wanted $year instead of $year_. To disambiguate, you can use enclose the variable name in brackets like this:

${year}_${i}.pdf

It's not bad practise to do this any time you are shoving variable expansions together. As you can see, it actually makes them stand out better to human eyes too.

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

Comments

1

Use ${var} instead:

year="2015"
for i in "${array[@]}"; do
    url="https://www.my-website.com/place/PdfLinkServlet?file=place${i}099%2Bno-display${year}_${i}.pdf"
    echo "$url"
done

Comments

0

Here is a little hack that also works well. And I use it for my projects frequently. Add the _ to the end of 2015 in the variable year like year="2015_" and remove the _ from the url variable and join the two variables i and year together like $year$i

I added an arbitrary array so that the script can run.

#!/bin/bash
year="2015_"
array=(web03 web04 web05 web06 web07)
for i in "${array[@]}";
do
url="https://www.my-website.com/place/PdfLinkServlet?file=\place\\$i\099%2Bno-display\\$year$i.pdf"
echo $url
done

1 Comment

This is a hack that serves no purpose. Use the correct variable notation.

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.