TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Metaprogramming in Bash

23 pointsby jandeboevrie9 months ago

5 comments

JNRowe9 months ago
If you&#x27;re a zsh user there is a fun^wquirky way to achieve similar functionality using the MULTI_FUNC_DEF¹ option. zsh allows you to define multiple functions at the same time, so you can parametrize functions with something like:<p><pre><code> build_ssh qa_ssh test_ssh() { echo ${(U)0%_*}_SYSTEMIP } build_ssh # Produces BUILD_SYSTEMIP qa_ssh # Produces QA_SYSTEMIP </code></pre> (You&#x27;d need the &#x27;P&#x27; flag to perform secondary expansion to get the value of *_SYSTEMIP if you were using this for the same reason as in the post).<p>You can even use brace expansion in your function definition, <i>iff</i> you define it using the function keyword like &quot;function {build,qa,test}_ssh()&quot;.<p>---<p>There might be a nice solution to this with fish too, as you could create per-machine symlinks in your ~&#x2F;.config&#x2F;fish&#x2F;functions to add a new machine.<p>¹ <a href="https:&#x2F;&#x2F;zsh.sourceforge.io&#x2F;Doc&#x2F;Release&#x2F;Options.html" rel="nofollow">https:&#x2F;&#x2F;zsh.sourceforge.io&#x2F;Doc&#x2F;Release&#x2F;Options.html</a>
评论 #41274080 未加载
000ooo0009 months ago
FYI one can avoid duping a command to echo it out as in some of the examples by using set -x (set -o xtrace). It can be disabled with set +x afterwards, or you can run it and your desired command in a subshell if performance is not a priority.<p><pre><code> ( set -x ssh ... )</code></pre>
loa_in_9 months ago
Having two copies of cmdline in the function is not a good design and probably most easily avoided with metaprogramming by building the cmdline first and then using it to echo and run it.<p>I do suspect the examples are intentionally very simplified though.
mcint9 months ago
I&#x27;m partial to defining echoeval()<p><pre><code> echoeval(){ CMD=&quot;$@&quot; echo &quot;$ $CMD&quot; eval &quot;$CMD&quot; } echoeval ssh test -A </code></pre> Variants that take a first parameter for coloring output, directing to stdout&#x2F;stderr, or (for one-shot commands) variant that colors output based on return value -- are functions I have written.
Tyr429 months ago
I like it, but once you get that far it&#x27;s probably better to have a tiny python script parse the config file and then use it.