0

When I am running following bash script-

#!/bin/bash
items="b.js
   a.js
   c.js"
startScript='<script src="'
endScript='"></script>'
for item in $items
do
  echo $startScript$item$endScript
done

Output:

 <script src="c.js"></script>
 <script src="a.js"></script>
 <script src="b.js"></script>

I want to run this for loop inside generated html file via a bash script. For loop is not working here.

#!/bin/bash
items="b.js
   a.js
   c.js"
startScript='<script src="'
endScript='"></script>'
cat << noEcho
<HTML>
<HEAD>
<TITLE>  Bash Script  </TITLE>
</HEAD>
<BODY>
for item in $items
do
 echo $startScript $item $endScript
done
</BODY>
</HTML>
noEcho
9
  • Don't store lists in strings -- use arrays for that. files=( b.js a.js c.js ), then for item in "${files[@]}"; ... Commented Sep 16, 2016 at 23:11
  • First, /bin/sh isn't always bash. Second, how is this not working? Third, I'd prefer printf to echo. Fourth, why bash instead of perl? Commented Sep 16, 2016 at 23:11
  • And you need to use $() if you want to substitute the output of some code into heredoc body text. Commented Sep 16, 2016 at 23:12
  • Also, you're never assigning anything to $items, so I don't know why you'd expect for item in $items to do anything useful even if you did properly have it inside of a command substitution. Commented Sep 16, 2016 at 23:13
  • @CharlesDuffy if I am using array getting Syntax error: "(" unexpected and for this "${files[@]}" -- Bad substitution Commented Sep 16, 2016 at 23:16

1 Answer 1

3

Simple example with the most glaring bugs fixed:

#!/bin/bash
files=( b.js a.js c.js)
startScript='<script src="'
endScript='"></script>'
cat << noEcho
<html><head><title>Bash Script</title></head><body>
$(
for file in "${files[@]}"; do
 echo "${startScript}${file}${endScript}"
done
)
</body></html>
noEcho

You can see the above running, with its output, at http://ideone.com/rSsO9H.

Some notes:

  • Don't do this. Really. Use a real template language that understands HTML syntax and knows how to escape content properly; you'll find securing this kind of code next to impossible if/when dealing with dynamic data.
  • Strings are not arrays. If you want an array, use an actual array.
  • If you want the output of a given piece of code to be substituted into a string (or, in this case, a heredoc), it needs to be in a command substitution: $()
Sign up to request clarification or add additional context in comments.

Comments

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.