如何从数组和命令模板中生成bash命令?
现在我使用此bash命令:
$ yarn b types && yarn w types && yarn g types && yarn s types
是否可以在bash中生成这样的命令? (伪代码):
$ exec ['b', 'w', 'g', 's'].map(input => `yarn ${input} types`).join(" && ")
如果可能的话,哪种语法在这里?
我要在我的package.json文件(节点)中使用此脚本。纱线工作区foreach在这里不合适,因为其输出差
Now I use this bash command:
$ yarn b types && yarn w types && yarn g types && yarn s types
Is it possible to generate command like this in bash? (pseudo code):
$ exec ['b', 'w', 'g', 's'].map(input => `yarn ${input} types`).join(" && ")
If it is possible, which syntax will be here?
I am going to use this script in my package.json file (node). yarn workspaces foreach not suitable here, because of its poor output
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
良好的实践替代方法:使用循环
代码生成具有严重的安全性,并且通常仅适用于专家。此外,在当前情况下,您不需要它:循环就足够了。
...具有相同的行为,如果有任何
YARN B类型
,YARN W类型
,YARN G类型
或<代码>纱线类型失败,如果全部四个成功,则以成功/零状态退出。作为单线,这将是:
如果您的物品在数组中,这不会以任何实质性的方式变化;如果有:
...然后,只需
bueldall BWG S
bueldall“ $ {type [@]}”
您要求的内容:执行代码
生成之前,请先执行任何操作您在自己的代码中看到了这里,查看 bashfaq#48 关于与
评估。
$ {var@q}
扩展需要bash 5.0或更新;对于较旧版本的bash,printf%q
是逃避变量内容的替代方法,可以安全解析作为代码。请注意,这并不比上面的替代方案更短或更可读,并且仍然涉及循环!:
用作true
的同义词;它使我们能够对循环进行所有相同的迭代,无条件准备&amp;&amp;
。支持较旧版本的bash的版本是:
Good-Practice Alternative: Use A Loop
Code generation has serious security implications and is generally only for experts. Moreover, in present circumstances, you don't need it: a loop will suffice.
...has identical behavior, exiting early with a nonzero status if any of
yarn b type
,yarn w type
,yarn g type
oryarn s type
fails, and exiting with a successful/zero status if all four succeed.As a one-liner, this would be:
This doesn't change in any substantial way if your items are in an array; if you have:
...then, just replace
buildAll b w g s
withbuildAll "${types[@]}"
What You Asked For: Performing Code Generation
Before doing anything you saw here in your own code, review BashFAQ #48 regarding the security issues associated with
eval
.The
${var@Q}
expansion requires bash 5.0 or newer; for older versions of bash,printf %q
is the alternate way to escape variables' contents to be safe to parse as code. Note that this isn't any shorter or more readable than the alternatives above, and still involves a loop!:
is used as a synonym totrue
; it lets us make all iterations of our loop identical, unconditionally prepending a&&
.The version with support for older versions of bash is: