22

How can I concatenate a shell variable to other other parameters in my command lines?

For example,

#!/bin/sh
WEBSITE="danydiop" 
/usr/bin/mysqldump --opt -u root --ppassword $WEBSITE > $WEBSITE.sql

I need to concatenate .sql to $WEBSITE

3 Answers 3

33

Use ${ } to enclosure a variable.

Without curly brackets:

VAR="foo"
echo $VAR
echo $VARbar

would give

foo

and nothing, because the variable $VARbar doesn't exist.

With curly brackets:

VAR="foo"
echo ${VAR}
echo ${VAR}bar

would give

foo
foobar

Enclosing the first $VAR is not necessary, but a good practice.

For your example:

#!/bin/sh
WEBSITE="danydiop" 
/usr/bin/mysqldump --opt -u root --ppassword ${WEBSITE} > ${WEBSITE}.sql

This works for bash, zsh, ksh, maybe others too.

3
  • 3
    This works for all Bourne-style shells (Bourne, POSIX, bash, ksh, zsh), C-style shells (csh, tcsh), and even in fish without the braces. So it's really universal amongst unix shells. I wouldn't call the braces good practice. But I do call systematically using double quotes around variable substitutions good practice. Commented Jan 4, 2011 at 20:17
  • 1
    @Gilles, I'd go further and say than not using double quotes around variable substitutions is very bad practice. Commented Jul 27, 2016 at 14:46
  • Also, take care that ${ } is not concatenation in any sense. For example, ELP=elp && echo $ELP && man --h${EPL} does not work. Commented Jun 17, 2019 at 20:03
4

Just concatenate the variable contents to whatever else you want to concatenate, e.g.

/usr/bin/mysqldump --opt -u root --ppassword "$WEBSITE" > "$WEBSITE.sql"

The double quotes are unrelated to concatenation: here >$WEBSITE.sql would have worked too. They are needed around variable expansions when the value of the variable might contain some shell special characters (whitespace and \[?*). I strongly recommend putting double quotes around all variable expansions and command substitutions, i.e., always write "$WEBSITE" and "$(mycommand)".

For more details, see $VAR vs ${VAR} and to quote or not to quote.

2

I usually use quotes, e.g. echo "$WEBSITE.sql".

So you could write it like:

#!/bin/sh
WEBSITE="danydiop" 
/usr/bin/mysqldump --opt -u root --ppassword $WEBSITE > "$WEBSITE.sql"
1
  • 3
    This does work since . isn't a valid character in a variable name; see wag's answer if you want to concatenate a string that does start with valid characters (e.g. "$WEBSITEsql" wouldn't work) Commented Jan 4, 2011 at 14:58

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.