user1052448
user1052448

Reputation: 433

How to pass multiple variables in shell script

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?

Upvotes: 0

Views: 1289

Answers (1)

Karoly Horvath
Karoly Horvath

Reputation: 96326

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.

Upvotes: 4

Related Questions