181

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tawheed
  • 5,565
  • 9
  • 36
  • 63

3 Answers3

293

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.

choroba
  • 231,213
  • 25
  • 204
  • 289
25

Use curly braces around the variable name:

`tail -1 ${filepath}_newstap.sh`
  • 1
    Don't you need double quotes? – michaelsnowden Oct 03 '15 at 21:25
  • @michaelsnowden Not necessarily. To be safe, yes, but the question explicitly stated a path with no spaces and further suggested that the trouble was `$filepath_newstap.sh` being interpreted as `${filepath_newstap}.sh` rather than the intended `${filepath}_newstap.sh`, which would solve the problem. –  Oct 03 '15 at 21:30
  • @michaelsnowden That tells me nothing I'm not already aware of. Why do you think double quotes are required? –  Oct 03 '15 at 21:33
  • Because you're trying to do string interpolation, and you need double quotes for that – michaelsnowden Oct 03 '15 at 22:12
  • @michaelsnowden Parameter expansion happens either in double quotes or outside of quotes completely. Single quotes or separating characters with quotes or other characters not valid in identifiers are the only way to prevent parameter expansion. For example, `"$filepath"_foo` and `${filepath}_foo` would both expand to `/tmp/name_foo`. However, `'$filepath'_foo`, `"$"filepath_foo`, and `$"filepath"_foo` would all avoid expansion completely. This is why `export PATH=$PATH:$addpath` works to add `:$addpath` (which would be subject to parameter expansion) to the `PATH` environment variable. –  Oct 03 '15 at 22:35
  • Incidentally, both of the other two answers contain the same response. The [accepted answer](http://stackoverflow.com/a/17622165/539810), however, also provides alternatives and an explanation for the behavior described by the OP. –  Oct 03 '15 at 22:45
  • @michaelsnowden You're probably confusing backticks ( `\`` ) with single-quotes ( `'` ) – user193130 May 13 '17 at 19:22
4

In Bash:

tail -1 ${filepath}_newstap.sh
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ani
  • 1,448
  • 1
  • 16
  • 38