0
#!/bin/bash rm all for f in assets/css/*.css; do printf "<style type='text/css' >\n" >> all cat $f >> all printf "</style>\n <!-----$f---->" >> all echo "$f copied" done 

I am using this code to copy all css content with the file names into a html file. This code works fine.

But the way strings are concatenated, it is mixing up the templates and the logic.

Can this be written more elegantly that has a template string like,

<style type='text/css'> ${cssContent} </style><!---${cssFileName}---> 

and an associative array like,

{ 'cssContent' : 'file content', 'cssFileName' : 'file name' } 

and a function as,

format(templateStr, assocArr) 

that returns me the formatted string?

2
  • Could you be more specific? How do you give those template string and assosiative array to the script?
    – yaegashi
    CommentedJun 8, 2015 at 10:05
  • the template string and associative array are two shell variables that can be initialised inside the shell script.... just they are meant for seperating out the constant strings and the values....
    – user93868
    CommentedJun 8, 2015 at 10:09

1 Answer 1

0

Bash apparently has assosiative array support, but I don't recommend to use it because there's no easy way to pass it to a function as argument. Instead this script defines key/value pairs interleaved in a simple array and pass them to format() as ordinal parameters.

#!/bin/bash format() ( T="$1" shift while test $# -ge 2; do eval "$1"'=$(echo "$2")' shift 2 done eval "cat <<END_OF_TEMPLATE $T END_OF_TEMPLATE" ) read -r -d '' templateStr <<'EOF' <style type='text/css'> ${cssContent} </style><!---${cssFileName}---> EOF assocArr=( cssFileName "abc.css" cssContent $'.abc {\n display: none;\n}\n' ) format "$templateStr" "${assocArr[@]}" 

Output:

$ bash format.sh <style type='text/css'> .abc { display: none; } </style><!---abc.css---> 

Note that $templateStr cannot contain line END_OF_TEMPLATE.

    You must log in to answer this question.