Soroush Rabiei
Soroush Rabiei

Reputation: 10878

Redirect IO inside shell script

I'm trying to recursively expand all .css files in a directory. I'm using beautifier (a node.js tool). It's supposed to to get a filename, expand its content, and write the result to stdout. So the following line do the job pretty well:

./node_modules/.bin/beautifier ./css/foo.css > ./css/bar.css 

But when I put all the things inside a script, it just prints all the output to the stdout and leaves all files empty after exit:

echo "Expanding CSS files..."
for css in `find . -type f -name \*.css -print`
do
    echo "Expanding $css"
    temp="$css.tmp"
    cp $css $temp
    ./node_modules/.bin/beautifier $temp>$css 
    rm $temp
done

what am I doing wrong here?

Upvotes: 2

Views: 88

Answers (2)

Reinstate Monica Please
Reinstate Monica Please

Reputation: 11653

This isn't really an answer, but again your script will incorrectly split files with spaces. You should do something like below instead

#!/bin/bash
echo "Expanding CSS files..."
while IFS= read -r -d '' css
do
   echo "Expanding $css"
   temp="$css.tmp"
   echo cp "$css" "$temp"
   echo ./node_modules/.bin/beautifier "$temp" '>' "$css"
   echo rm "$temp"
done < <(find . -type f -name \*.css -print0)

I put echo's everywhere and quotes around > so it doesn't actually do anything other than show you what it would do. Could also do #!/bin/bash -x which would show what it's doing while executing commands.

Upvotes: 1

rpax
rpax

Reputation: 4496

Putting the variables inside "" solves the problem

echo "Expanding CSS files..."
for css in `find . -type f -name \*.css -print`
do
   echo "Expanding $css"
   temp="$css.tmp"
   cp $css $temp
   ./node_modules/.bin/beautifier "$temp" > "$css" 
   rm $temp

done

EDIT: The real problem was there were no spaces between > . But as @Biffen pointed, this is a good practice. If the line were like this,

"$temp">"$css"

An error raises:

unexpected EOF while looking for matching `"'
syntax error: unexpected end of file

So it's easier to debug.

Although my answer works, @Briffen is discovered the real error, the credit should go to him.

Upvotes: 0

Related Questions