bash-hackers-wiki/scripting/style/index.html

96 lines
61 KiB
HTML
Raw Normal View History

<!doctype html><html lang=en class=no-js> <head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><link href=https://flokoe.github.io/bash-hackers-wiki/scripting/style/ rel=canonical><link href=../processtree/ rel=prev><link href=../terminalcodes/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.5.44"><title>Scripting with style - The Bash Hackers Wiki</title><link rel=stylesheet href=../../assets/stylesheets/main.0253249f.min.css><link rel=stylesheet href=../../assets/stylesheets/palette.06af60db.min.css><link rel=preconnect href=https://fonts.gstatic.com crossorigin><link rel=stylesheet href="https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,700,700i%7CRoboto+Mono:400,400i,700,700i&display=fallback"><style>:root{--md-text-font:"Roboto";--md-code-font:"Roboto Mono"}</style><script>__md_scope=new URL("../..",location),__md_hash=e=>[...e].reduce(((e,_)=>(e<<5)-e+_.charCodeAt(0)),0),__md_get=(e,_=localStorage,t=__md_scope)=>JSON.parse(_.getItem(t.pathname+"."+e)),__md_set=(e,_,t=localStorage,a=__md_scope)=>{try{t.setItem(a.pathname+"."+e,JSON.stringify(_))}catch(e){}}</script></head> <body dir=ltr data-md-color-scheme=default data-md-color-primary=indigo data-md-color-accent=indigo> <input class=md-toggle data-md-toggle=drawer type=checkbox id=__drawer autocomplete=off> <input class=md-toggle data-md-toggle=search type=checkbox id=__search autocomplete=off> <label class=md-overlay for=__drawer></label> <div data-md-component=skip> <a href=#scripting-with-style class=md-skip> Skip to content </a> </div> <div data-md-component=announce> </div> <header class=md-header data-md-component=header> <nav class="md-header__inner md-grid" aria-label=Header> <a href=../.. title="The Bash Hackers Wiki" class="md-header__button md-logo" aria-label="The Bash Hackers Wiki" data-md-component=logo> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a3 3 0 0 0 3-3 3 3 0 0 0-3-3 3 3 0 0 0-3 3 3 3 0 0 0 3 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54"/></svg> </a> <label class="md-header__button md-icon" for=__drawer> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M3 6h18v2H3zm0 5h18v2H3zm0 5h18v2H3z"/></svg> </label> <div class=md-header__title data-md-component=header-title> <div class=md-header__ellipsis> <div class=md-header__topic> <span class=md-ellipsis> The Bash Hackers Wiki </span> </div> <div class=md-header__topic data-md-component=header-topic> <span class=md-ellipsis> Scripting with style </span> </div> </div> </div> <form class=md-header__option data-md-component=palette> <input class=md-option data-md-color-media data-md-color-scheme=default data-md-color-primary=indigo data-md-color-accent=indigo aria-label="Switch to dark mode" type=radio name=__palette id=__palette_0> <label class="md-header__button md-icon" title="Switch to dark mode" for=__palette_1 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a4 4 0 0 0-4 4 4 4 0 0 0 4 4 4 4 0 0 0 4-4 4 4 0 0 0-4-4m0 10a6 6 0 0 1-6-6 6 6 0 0 1 6-6 6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> <input class=md-option data-md-color-media data-md-color-scheme=slate data-md-color-primary=indigo data-md-color-accent=indigo aria-label="Switch to light mode" type=radio name=__palette id=__palette_1> <label class="md-header__button md-icon" title="Switch to light mode" for=__palette_0 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6a6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> </form> <script>var palette=__md_get("__palette");if(palette&&palette.color){if("(prefers-color-scheme)"===palette.color.media){var media=matchMedia("(prefe
some_other_option
</code></pre></div> <p><u><strong>Indention using two spaces:</strong></u></p> <div class=highlight><pre><span></span><code>activate some_very_long_option \
some_other_option
</code></pre></div> <p>Personally, with some exceptions, I prefer the first form because it supports the visual impression of "these belong together".</p> <h3 id=breaking-compound-commands>Breaking compound commands<a class=headerlink href=#breaking-compound-commands title="Permanent link">&para;</a></h3> <p><a href=../../syntax/ccmd/intro/ >Compound commands</a> form the structures that make a shell script different from a stupid enumeration of commands. Usually they contain a kind of "head" and a "body" that contains command lists. This type of compound command is relatively easy to indent.</p> <p>I'm used to (not all points apply to all compound commands, just pick the basic idea):</p> <ul> <li>put the introducing keyword and the initial command list or parameters on one line ("head")</li> <li>put the "body-introducing" keyword on the same line</li> <li>the command list of the "body" on separate lines, indented by two spaces</li> <li>put the closing keyword on a separated line, indented like the initial introducing keyword</li> </ul> <p>What?! Well, here again:</p> <h5 id=symbolic>Symbolic<a class=headerlink href=#symbolic title="Permanent link">&para;</a></h5> <div class=highlight><pre><span></span><code>HEAD_KEYWORD parameters; BODY_BEGIN
BODY_COMMANDS
BODY_END
</code></pre></div> <h5 id=ifthenelifelse>if/then/elif/else<a class=headerlink href=#ifthenelifelse title="Permanent link">&para;</a></h5> <p>This construct is a bit special, because it has keywords (<code>elif</code>, <code>else</code>) "in the middle". The visually appealing way is to indent them like this:</p> <div class=highlight><pre><span></span><code>if ...; then
...
elif ...; then
...
else
...
fi
</code></pre></div> <h5 id=for>for<a class=headerlink href=#for title="Permanent link">&para;</a></h5> <div class=highlight><pre><span></span><code>for f in /etc/*; do
...
done
</code></pre></div> <h5 id=whileuntil>while/until<a class=headerlink href=#whileuntil title="Permanent link">&para;</a></h5> <div class=highlight><pre><span></span><code>while [[ $answer != [YyNn] ]]; do
...
done
</code></pre></div> <h5 id=the-case-construct>The case construct<a class=headerlink href=#the-case-construct title="Permanent link">&para;</a></h5> <p>The <code>case</code> construct might need a bit more discussion here, since its structure is a bit more complex.</p> <p>In general, every new "layer" gets a new indentation level:</p> <div class=highlight><pre><span></span><code>case $input in
hello)
echo &quot;You said hello&quot;
;;
bye)
echo &quot;You said bye&quot;
if foo; then
bar
fi
;;
*)
echo &quot;You said something weird...&quot;
;;
esac
</code></pre></div> <p>Some notes:</p> <ul> <li>if not 100% needed, the optional left parenthesis on the pattern is not used</li> <li>the patterns (<code>hello)</code>) and the corresponding action terminator (<code>;;</code>) are indented at the same level</li> <li>the action command lists are indented one more level (and continue to have their own indentation, if needed)</li> <li>though optional, the very last action terminator is given</li> </ul> <h2 id=syntax-and-coding-guidelines>Syntax and coding guidelines<a class=headerlink href=#syntax-and-coding-guidelines title="Permanent link">&para;</a></h2> <h3 id=cryptic-constructs>Cryptic constructs<a class=headerlink href=#cryptic-constructs title="Permanent link">&para;</a></h3> <p>Cryptic constructs, we all know them, we all love them. If they are not 100% needed, avoid them, since nobody except you may be able to decipher them.</p> <p>It's - just like in C - the middle ground between smart, efficient and readable.</p> <p>If you need to use a cryptic construct, include a comment that explains what your "monster" does.</p> <h3 id=variable-names>Variable names<a class=headerlink href=#variable-names title="Permanent link">&para;</a></h3> <p>Since all reserved variables are <code>UPPERCASE</code>, the safest way is to only use <code>lowercase</code> variable names. This is true for reading user input, loop counting variables, etc., ... (in the example: <code>file</code>)</p> <ul> <li>prefer <code>lowercase</code> variables</li> <li>if you use <code>UPPERCASE</code> names, <strong>do not use reserved variable names</strong> (see <a href=http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08>SUS</a> for an incomplete list)</li> <li> <p>if you use <code>UPPERCASE</code> names, prepend the name with a unique prefix (<code>MY_</code> in the example below)</p> <h1 id=binbash>!/bin/bash<a class=headerlink href=#binbash title="Permanent link">&para;</a></h1> <h1 id=the-prefix-my_>the prefix 'MY_'<a class=headerlink href=#the-prefix-my_ title="Permanent link">&para;</a></h1> <p>MY_LOG_DIRECTORY=/var/adm/</p> <p>for file in "$MY_LOG_DIRECTORY"/*; do echo "Found Logfile: $file" done</p> </li> </ul> <h3 id=variable-initialization>Variable initialization<a class=headerlink href=#variable-initialization title="Permanent link">&para;</a></h3> <p>As in C, it's always a good idea to initialize your variables, though, the shell will initialize fresh variables itself (better: Unset variables will generally behave like variables containing a null string).</p> <p>It's no problem to pass an <strong>environment variable</strong> to the script. If you blindly assume that all variables you use for the first time are <strong>empty</strong>, anybody can <strong>inject</strong> content into a variable by passing it via the environment.</p> <p>The solution is simple and effective: <strong>Initialize them</strong></p> <div class=highlight><pre><span></span><code>my_input=&quot;&quot;
my_array=()
my_number=0
</code></pre></div> <p>If you do that for every variable you use, then you also have some in-code documentation for them.</p> <h3 id=parameter-expansion>Parameter expansion<a class=headerlink href=#parameter-expansion title="Permanent link">&para;</a></h3> <p>Unless you are really sure what you're doing, <strong>quote every parameter expansion</strong>.</p> <p>There are some cases where this isn't needed from a technical point of view, e.g.</p> <ul> <li>inside <code>[[ ... ]]</code> (other than the RHS of the <code>==</code>, <code>!=</code>, and <code>=~</code> operators)</li> <li>the parameter (<code>WORD</code>) in <code>case $WORD in ....</code></li> <li>variable assignment: <code>VAR=$WORD</code></li> </ul> <p>But quoting these is never a mistake. If you quote every parameter expansion, you'll be safe.</p> <p>If you need to parse a parameter as a list of words, you can't quote, of course, e.g.</p> <div class=highlight><pre><span></span><code>list=&quot;one two three&quot;
# you MUST NOT quote $list here
for word in $list; do
...
done
</code></pre></div> <h3 id=function-names>Function names<a class=headerlink href=#function-names title="Permanent link">&para;</a></h3> <p>Function names should be all <code>lowercase</code> and meaningful. The function names should be human readable. A function named <code>f1</code> may be easy and quick to write down, but for debugging and especially for other people, it reveals nothing. Good names help document your code without using extra comments.</p> <p><strong>do not use command names for your functions</strong>. e.g. naming a script or function <code>test</code>, will collide with the UNIX <code>test</code> command.</p> <p>Unless absolutely necessary, only use alphanumeric characters and the underscore for function names. <code>/bin/ls</code> is a valid function name in Bash, but is not a good idea.</p> <h3 id=command-substitution>Command substitution<a class=headerlink href=#command-substitution title="Permanent link">&para;</a></h3> <p>As noted in <a href=../../syntax/expansion/cmdsubst/ >the article about command substitution</a>, you should use the <code>$( ... )</code> form.</p> <p>If portability is a concern, use the backquoted form <code>` ... `</code>.</p> <p>In any case, if other expansions and word splitting are not wanted, you should quote the command substitution!</p> <h3 id=eval>Eval<a class=headerlink href=#eval title="Permanent link">&para;</a></h3> <p>Well, like Greg says: <strong>"If eval is the answer, surely you are asking the wrong question."</strong></p> <p>Avoid it, unless absolutely neccesary:</p> <ul> <li><code>eval</code> can be your neckshot</li> <li>there are most likely other ways to achieve what you want</li> <li>if possible, re-think the way your script works, if it seems you can't avoid <code>eval</code> with your current method</li> <li>if you really, really, have to use it, then take care, and be sure about what you're doing</li> </ul> <h2 id=basic-structure>Basic structure<a class=headerlink href=#basic-structure title="Permanent link">&para;</a></h2> <p>The basic structure of a script simply reads:</p> <div class=highlight><pre><span></span><code>#!SHEBANG
CONFIGURATION_VARIABLES
FUNCTION_DEFINITIONS
MAIN_CODE
</code></pre></div> <h3 id=the-shebang>The shebang<a class=headerlink href=#the-shebang title="Permanent link">&para;</a></h3> <p>If possible (I know it's not always possible!), use a <a href=../../dict/interpreter_directive/ >shebang</a>.</p> <p>Be careful with <code>/bin/sh</code>: The argument that "on Linux <code>/bin/sh</code> is Bash" <strong>is a lie</strong> (and technically irrelevant)</p> <p>The shebang serves two purposes for me:</p> <ul> <li>it specifies the interpreter to be used when the script file is called directly: If you code for Bash, specify <code>bash</code>!</li> <li>it documents the desired interpreter (so: use <code>bash</code> when you write a Bash-script, use <code>sh</code> when you write a general Bourne/POSIX script, ...)</li> </ul> <h3 id=configuration-variables>Configuration variables<a class=headerlink href=#configuration-variables title="Permanent link">&para;</a></h3> <p>I call variables that are meant to be changed by the user "configuration variables" here.</p> <p>Make them easy to find (directly at the top of the script), give them meaningful names and maybe a short comment. As noted above, use <code>UPPERCASE</code> for them only when you're sure about what you're doing. <code>lowercase</code> will be the safest.</p> <h3 id=function-definitions>Function definitions<a class=headerlink href=#function-definitions title="Permanent link">&para;</a></h3> <p>Unless there are reasons not to, all function definitions should be declared before the main script code runs. This gives a far better overview and ensures that all function names are known before they are used.</p> <p>Since a function isn't parsed before it is executed, you usually don't have to ensure they're in a specific order.</p> <p>The portable form of the function definition should be used, without the <code>function</code> keyword (here using the <a href=../../syntax/ccmd/grouping_plain/ >grouping compound command</a>):</p> <div class=highlight><pre><span></span><code>getargs() {
...
}
</code></pre></div> <p>Speaking about the command grouping in function definitions using <code>{ ...; }</code>: If you don't have a good reason to use another compound command directly, you should always use this one.</p> <h2 id=behaviour-and-robustness>Behaviour and robustness<a class=headerlink href=#behaviour-and-robustness title="Permanent link">&para;</a></h2> <h3 id=fail-early>Fail early<a class=headerlink href=#fail-early title="Permanent link">&para;</a></h3> <p><strong>Fail early</strong>, this sounds bad, but usually is good. Failing early means to error out as early as possible when checks indicate an error or unmet condition. Failing early means to error out <strong>before</strong> your script begins its work in a potentially broken state.</p> <h3 id=availability-of-commands>Availability of commands<a class=headerlink href=#availability-of-commands title="Permanent link">&para;</a></h3> <p>If you use external commands that may not be present on the path, or not installed, check for their availability, then tell the user they're missing.</p> <p>Example:</p> <div class=highlight><pre><span></span><code>my_needed_commands=&quot;sed awk lsof who&quot;
missing_counter=0
for needed_command in $my_needed_commands; do
if ! hash &quot;$needed_command&quot; &gt;/dev/null 2&gt;&amp;1; then
printf &quot;Command not found in PATH: %s\n&quot; &quot;$needed_command&quot; &gt;&amp;2
((missing_counter++))
fi
done
if ((missing_counter &gt; 0)); then
printf &quot;Minimum %d commands are missing in PATH, aborting\n&quot; &quot;$missing_counter&quot; &gt;&amp;2
exit 1
fi
</code></pre></div> <h3 id=exit-meaningfully>Exit meaningfully<a class=headerlink href=#exit-meaningfully title="Permanent link">&para;</a></h3> <p>The <a href=../../dict/exit_status/ >exit code</a> is your only way to directly communicate with the calling process without any special provisions.</p> <p>If your script exits, provide a meaningful exit code. That minimally means:</p> <ul> <li><code>exit 0</code> (zero) if everything is okay</li> <li><code>exit 1</code> - in general non-zero - if there was an error</li> </ul> <p>This, <strong>and only this</strong>, will enable the calling component to check the operation status of your script.</p> <p>You know: <strong>"One of the main causes of the fall of the Roman Empire was that, lacking zero, they had no way to indicate successful termination of their C programs."</strong> <em>-- Robert Firth</em></p> <h2 id=misc>Misc<a class=headerlink href=#misc title="Permanent link">&para;</a></h2> <h3 id=output-and-appearance>Output and appearance<a class=headerlink href=#output-and-appearance title="Permanent link">&para;</a></h3> <ul> <li>if the script is interactive, if it works for you and if you think this is a nice feature, you can try to <a href=../../snipplets/screen_saverestore/ >save the terminal content and restore it</a> after execution</li> <li>output clean and understandable screen messages</li> <li>if applicable, you can use colors or specific prefixes to tag error and warning messages<ul> <li>make it easy for the user to identify those messages</li> </ul> </li> <li>write normal output to <code>STDOUT</code>. write error, warning and diagnostic messages to <code>STDERR</code><ul> <li>enables message filtering</li> <li>keeps the script from mixing output data with diagnostic, or error messages</li> <li>if the script gives syntax help (<code>-?</code> or <code>-h</code> or <code>--help</code> arguments), it should go to <code>STDOUT</code></li> </ul> </li> <li>if applicable, write error/diagnostic messages to a logfile<ul> <li>avoids screen clutter</li> <li>messages are available for diagnostic use</li> </ul> </li> </ul> <h3 id=input>Input<a class=headerlink href=#input title="Permanent link">&para;</a></h3> <ul> <li>never blindly assume anything. If you want the user to input a number, <strong>check for numeric input, leading zeros</strong>, etc. If you have specific format or content needs, <strong>always validate the input!</strong></li> </ul> <h3 id=tooling>Tooling<a class=headerlink href=#tooling title="Permanent link">&para;</a></h3> <ul> <li>some of these guidelines, such as indentation, positioning of "body-introducing" keywords, and portable function declarations, can be enforced by <a href=https://github.com/mvdan/sh>shfmt</a></li> </ul> <aside class=md-source-file> <span class=md-source-file__fact> <span class=md-icon title="Last update"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M21 13.1c-.1 0-.3.1-.4.2l-1 1 2.1 2.1 1-1c.2-.2.2-.6 0-.8l-1.3-1.3c-.1-.1-.2-.2-.4-.2m-1.9 1.8-6.1 6V23h2.1l6.1-6.1zM12.5 7v5.2l4 2.4-1 1L11 13V7zM11 21.9c-5.1-.5-9-4.8-9-9.9C2 6.5 6.5 2 12 2c5.3 0 9.6 4.1 10 9.3-.3-.1-.6-.2-1-.2s-.7.1-1 .2C19.6 7.2 16.2 4 12 4c-4.4 0-8 3.6-8 8 0 4.1 3.1 7.5 7.1 7.9l-.1.2z"/></svg> </span> <span class="git-revision-date-localized-plugin git-revision-date-localized-plugin-date">November 13, 2024</span> </span> <span class=md-source-file__fact> <span class=md-icon title=Created> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M14.47 15.08 11 13V7h1.5v5.25l3.08 1.83c-.41.28-.79.62-1.11 1m-1.39 4.84c-.36.05-.71.08-1.08.08-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8c0 .37-.03.72-.08 1.08.69.1 1.33.32 1.92.64.1-.56.16-1.13.16-1.72 0-5.5-4.5-10-10-10S2 6.5 2 12s4.47 10 10 10c.59 0 1.16-.06 1.72-.16-.32-.59-.54-1.23-.64-1.92M18 15v3h-3v2h3v3h2v-3h3v-2h-3v-3z"/></svg> </span> <span class="git-revision-date-localized-plugin git-revision-date-localized-plugin-date">November 13, 2024</span> </span> </aside> <h2 id=__comments>Comments</h2> <script src=https://giscus.app/client.js data-repo=flokoe/bash-hackers-wiki data-re
</script> <script>
var giscus = document.querySelector("script[src*=giscus]")
/* Set palette on initial load */
var palette = __md_get("__palette")
if (palette && typeof palette.color === "object") {
var theme = palette.color.scheme === "slate" ? "dark" : "light"
giscus.setAttribute("data-theme", theme)
}
/* Register event handlers after documented loaded */
document.addEventListener("DOMContentLoaded", function() {
var ref = document.querySelector("[data-md-component=palette]")
ref.addEventListener("change", function() {
var palette = __md_get("__palette")
if (palette && typeof palette.color === "object") {
var theme = palette.color.scheme === "slate" ? "dark" : "light"
/* Instruct Giscus to change theme */
var frame = document.querySelector(".giscus-frame")
frame.contentWindow.postMessage(
{ giscus: { setConfig: { theme } } },
"https://giscus.app"
)
}
})
})
</script> </article> </div> <script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script> </div> <button type=button class="md-top md-icon" data-md-component=top hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8z"/></svg> Back to top </button> </main> <footer class=md-footer> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class=md-copyright> Made with <a href=https://squidfunk.github.io/mkdocs-material/ target=_blank rel=noopener> Material for MkDocs </a> </div> </div> </div> </footer> </div> <div class=md-dialog data-md-component=dialog> <div class="md-dialog__inner md-typeset"></div> </div> <script id=__config type=application/json>{"base": "../..", "features": ["navigation.instant", "navigation.tracking", "navigation.tabs", "navigation.sections", "navigation.top", "content.action.view", "content.action.edit", "search.suggest", "search.highlight", "content.code.copy"], "search": "../../assets/javascripts/workers/search.6ce7567c.min.js", "translations": {"clipboard.copied": "Copied to clipboard", "clipboard.copy": "Copy to clipboard", "search.result.more.one": "1 more on this page", "search.result.more.other": "# more on this page", "search.result.none": "No matching documents", "search.result.one": "1 matching document", "search.result.other": "# matching documents", "search.result.placeholder": "Type to start searching", "search.result.term.missing": "Missing", "select.version": "Select version"}}</script> <script src=../../assets/javascripts/bundle.83f73b43.min.js></script> </body> </html>