Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

thanks

share|improve this question
add comment

3 Answers

up vote 11 down vote accepted

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.

share|improve this answer
2  
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 Jan 4 '11 at 20:17
add comment

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"
share|improve this answer
2  
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 4 '11 at 14:58
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.