0

I have a shell script that I'm trying to write to a file using multiple variables, but one of them is being ignored.

#!/bin/bash

dir=/folder
name=bob
date=`date +%Y`

command > $dir/$name_$date.ext

The $name is being ignored. How can I fix this?

5
  • 8
    Use: command > "${dir}/${name}_${date}.ext" Commented Oct 29, 2015 at 14:50
  • 1
    set -u might be a good idea. Commented Oct 29, 2015 at 14:56
  • 2
    Your code uses the var name_. When you cannot change the last line into fields with {}, you can work around with name_=bob_. Commented Oct 29, 2015 at 15:11
  • 3
    That workaround is evil... Just don't. Commented Oct 29, 2015 at 15:23
  • @Karoly: It is evil indeed, I included it for showing what is happening and encouraging the normal method showed by anubhava. Commented Oct 29, 2015 at 15:53

1 Answer 1

4

Have you noticed that the _ was "ignored" as well? That's a big hint.
If you use set -u, you'll see the following:

-bash: name_: unbound variable

The way bash parses it, the underscore is part of the variable name.

There are several ways to fix the problem.
The cleanest is the ${var} construct which separate the variable name from its surroundings.
You can also use quotation in various ways to force the right parsing, e.g.: "$dir/$name""_$date.ext"

And in case your variables might contain spaces (now, or in the future) use quotation for words.

command >"$dir/${name}_$date.ext"
command >"${dir}/${name}_${date}.ext"

Both these are fine, just pick one style and stick to it.

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

1 Comment

Ah, forgot that _ can be part of a variable. Thanks!

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.