如何在bash命令行上输出文件列表
我正在使用handlebars.js为我们的单页应用程序呈现客户端模板(在node.js服务器端使用Jade)。
我想预编译服务器端的句柄模板,并把它们打包成一个JS文件发送给客户端。
目前,我使用handlebars
来编译模板,如下所示:
$ handlebars template1.handlebars template2.handlebars -f precompiled_templates.js
我想写一个bash脚本,可以读取目录中的所有*.handlebars
文件,然后通过*.handlebars
编译器运行它们。 所以,如果我有一个像这样的目录:
templates/ temp1.handlebars temp2.handlebars temp3.handlebars temp4.handlebars
在templates目录中运行我的bash脚本(或者一行命令)本质上会运行下面的handlebars
命令:
$ handlebars temp1.handlebars temp2.handlebars temp3.handlebars temp4.handlebars -f precompiled_templates.js
有谁知道我可以写一个bash脚本来获取目录中的所有句柄文件到上面的命令行吗?
它看起来像你想要的东西类似
handlebars templates/*.handlebars -f precompiled_templates.js
除非您最终会在每个文件的前面添加“模板”。 我喜欢的方法需要两行:
files=( templates/*.handlebars ) handlebars "${files[@]#templates/}" -f precompiled_templates.js.
第一行将所有需要的文件放在一个数组中。 在第二行中,我们展开数组的内容,但从结果扩展中的每个元素中剥离“templates /”前缀。
在模板目录中执行:
handlebars `find -name *.handlebars` -f precompiled_templates.js
back-ticks意味着它会执行那个命令然后返回结果,所以你实际上是在它返回的每个文件上运行句柄。 正如上面所写的,将查找当前和子目录中的文件,所以确保你从正确的地方运行它。
在Bash中,可以使用双引号内的string来创build列表:
FILES="/etc/hosts /etc/passwd" for file in $FILES; do cat $file ; done <cat all files>
您也可以使用find和exec命令。
man [find | exec]获取更多信息