[英]Is it possible to redirect stdout to a non-stderr stream inside a shell script?
[英]Redirect IO inside shell script
我正在尝试以递归方式扩展目录中的所有.css
文件。 我正在使用美化工具(一个node.js工具)。 它应该获取文件名,扩展其内容,然后将结果写入stdout。 因此,以下代码可以很好地完成这项工作:
./node_modules/.bin/beautifier ./css/foo.css > ./css/bar.css
但是,当我将所有内容放入脚本时,它只是将所有输出打印到stdout
并在退出后将所有文件留空:
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
我在这里做错了什么?
这并不是一个真正的答案,但是您的脚本会再次错误地用空格分割文件。 您应该执行以下操作
#!/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)
我将echo
的位置无处不在,并用引号引起来>
因此除了向您展示它会做什么之外,它实际上没有做任何其他事情。 也可以执行#!/bin/bash -x
,这将显示执行命令时的操作。
将变量放在""
可以解决问题
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
编辑:真正的问题是>
之间没有空格。 但是正如@Biffen指出的那样,这是一个好习惯。 如果这样的话
"$temp">"$css"
引发错误:
unexpected EOF while looking for matching `"'
syntax error: unexpected end of file
因此更容易调试。
尽管我的回答有效,但@Briffen被发现是真正的错误,功劳应该归功于他。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.