EuGENE EuGENE - 7 months ago 12
Bash Question

Concatenate variables using expansion in bash

I'm trying to simplify a compilation line for

gcc
using exapansion variables properties of bash scripting.

Let's say I've defined a variable
SRC=src/
containing a folder of source files, and an additional variable
C_SOURCES=(source1.c source2.c ...)
countaining the source files themselves.

If I write something like
"${SRC}${C_SOURCES[@]}"
, the result is that only the first value in the
C_SOURCES
variable gets the value in
SRC
, so:
src/source1.c source2.c ...
. Which is not what I expected.

How should I rewrite the line with variable expansion so all values in
C_SOURCES
variable get the value in
SRC
variable?

123 123
Answer

You can use printf

C_SOURCES=('source1.c' 'source 2.c' 'source3.c' )

SRC='src/'

printf "'$SRC%s' " "${C_SOURCES[@]}"

outputs

'src/source1.c' 'src/source 2.c' 'src/source3.c'
Comments