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.

I am trying to iterate over an array of file names and substitute the file name inside an absolute path. The code is,

#!/bin/bash
jsArray=(moment.js datatable.js jquery.js jquery.tmpl.js dt_jq_ui.js report_app.js)
for f in "/path/to/res/${jsArray[@]}.js";
do
  echo "$f"
done

It returns,

/path/to/res/moment.js
datatable.js
jquery.js
jquery.tmpl.js
dt_jq_ui.js
report_app.js.js

Why does only the first element get prefixed, and only the last element get suffixed?

I expected entries like,

/path/to/res/moment.js
/path/to/res/datatable.js
..................
/path/to/res/report_app.js  
share|improve this question

2 Answers 2

up vote 4 down vote accepted

Because you told Bash to:

~$ echo "/path/to/res/${jsArray[@]}.js"
/path/to/res/moment.js datatable.js jquery.js jquery.tmpl.js dt_jq_ui.js report_app.js.js

You are just giving one long string. What you want to do is something like

~$ for f in "${jsArray[@]}.js"
     do echo "/path/to/res/$f"
   done
/path/to/res/moment.js
/path/to/res/datatable.js
/path/to/res/jquery.js
/path/to/res/jquery.tmpl.js
/path/to/res/dt_jq_ui.js
/path/to/res/report_app.js.js
share|improve this answer
    
i didn't expect shell expands the array values, so soon.. thank you folks.... –  Madhavan Kumar Jun 8 at 11:06

Because that's what you're giving your loop:

$ jsArray=(moment.js datatable.js jquery.js jquery.tmpl.js dt_jq_ui.js report_app.js)
$ echo "/path/to/res/${jsArray[@]}.js"
/path/to/res/moment.js datatable.js jquery.js jquery.tmpl.js dt_jq_ui.js report_app.js.js

Or, to take a simpler example:

$ arr=(a b c );
$ for f in "foo ${arr[@]} bar"; do echo "$f"; done
foo a
b
c bar

You are giving a string, an array and another string. Why would the shell append the string to each element? I's printing string,array,string, just like you told it to.

If you want to add a prefix and suffix to each element, you could do:

$ for f in "${jsArray[@]}";
do
  echo "/path/to/res/$f.js"
done
/path/to/res/moment.js.js
/path/to/res/datatable.js.js
/path/to/res/jquery.js.js
/path/to/res/jquery.tmpl.js.js
/path/to/res/dt_jq_ui.js.js
/path/to/res/report_app.js.js
share|improve this answer

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.