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.
#!/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?

share|improve this question
    
Could you be more specific? How do you give those template string and assosiative array to the script? –  yaegashi Jun 8 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.... –  Madhavan Kumar Jun 8 at 10:09

1 Answer 1

up vote 1 down vote accepted

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.

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.