3

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  
3

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
  • i didn't expect shell expands the array values, so soon.. thank you folks.... – user93868 Jun 8 '15 at 11:06
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy