Variable interpolation in the shell

BashShellUnix

Bash Problem Overview


I have a variable called filepath=/tmp/name.

To access the variable, I know that I can do this: $filepath

In my shell script I attempted to do something like this (the backticks are intended)

`tail -1 $filepath_newstap.sh`

This line fails, duuh!, because the variable is not called $filepath_newstap.sh

How do I append _newstap.sh to the variable name?

Please note that backticks are intended for the expression evaluation.

Bash Solutions


Solution 1 - Bash

Use

"$filepath"_newstap.sh

or

${filepath}_newstap.sh

or

$filepath\_newstap.sh

_ is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap.

You can use set -u to make the shell exit with an error when you reference an undefined variable.

Solution 2 - Bash

Use curly braces around the variable name:

`tail -1 ${filepath}_newstap.sh`

Solution 3 - Bash

In Bash:

tail -1 ${filepath}_newstap.sh

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontawheedView Question on Stackoverflow
Solution 1 - BashchorobaView Answer on Stackoverflow
Solution 2 - Bashuser539810View Answer on Stackoverflow
Solution 3 - BashvyomView Answer on Stackoverflow