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

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
aneuryzm
  • 1,925

3 Answers3

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.

wag
  • 35,944
  • 12
  • 67
  • 51
  • 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. – Gilles 'SO- stop being evil' Jan 04 '11 at 20:17
  • 1
    @Gilles, I'd go further and say than not using double quotes around variable substitutions is very bad practice. – Stéphane Chazelas Jul 27 '16 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. – yujaiyu Jun 17 '19 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"
Gert
  • 9,994
  • 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) – Michael Mrozek Jan 04 '11 at 14:58