1

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?

2
  • Don't know if it is a typo, but source 2.c will be two different elements in the array unless you quote it Commented Apr 28, 2016 at 9:53
  • @SaintHax An array is a variable. Commented Apr 28, 2016 at 10:06

2 Answers 2

3

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'
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, it works for me if i remove the single quotation marks around the $SRC%s term. Thank you very much!
@EuGENE Didn't know what you want to use the end product for so yeah just tweak it to fit your purposes :)
1

Try this:

PATHS=($(for x in ${C_SOURCES[@]}; do echo "$SRC/$x"; done))

I chose to include the / just to be sure. This won't handle filenames or paths with spaces in them properly.

1 Comment

It does not seem to work in the gcc instruction, as using echo in a for loop introduces newline characters at the end of "$SRC/$x". But thank you for your advice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.