bash-hackers-wiki/search/search_index.json

1 line
820 KiB
Bash

{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"The Bash Hackers Wiki","text":"<p>Under construction</p> <p>This is an archive of the old wiki.bash-hackers.org with the goal of preserving and improving the content by the community in a modern way and format.</p> <p>The most recent version of each page that had content was automatically converted to Markdown and can be found here. Pandoc did its best, but there is still some work to do as not all pages are formatted correctly. So for everyone who is interested in helping out, feel free to open PRs. Any help is welcome.</p> <p>This wiki is intended to hold documentation of any kind about GNU Bash. The main motivation was to provide human-readable documentation and information so users aren't forced to read every bit of the Bash manpage - which can be difficult to understand. However, the docs here are not meant as a newbie tutorial.</p> <p>This wiki and any programs found in this wiki are free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.</p> <p>This wiki and its programs are distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.</p> <p>You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.</p> <p>Stranger! Feel free to comment or edit the contents on GitHub. Use GitHub Issues to submit bugs and GitHub Discussions for enhancements, requests and general feedback/discussion.</p>","tags":["bash","shell","linux","scripting"]},{"location":"#scripting-and-general-information","title":"Scripting and general information","text":"<ul> <li>Bash v4 - a rough overview (unmaintained, since Bash 4 is more or less standard.md)</li> <li>style \u2013 an assorted collection of style and optic hints</li> <li>basics</li> <li>newbie_traps</li> <li>bashbehaviour</li> <li>posparams</li> <li>processtree</li> <li>obsolete</li> <li>nonportable</li> <li>debuggingtips</li> <li>terminalcodes</li> </ul>","tags":["bash","shell","linux","scripting"]},{"location":"#code-snippets","title":"Code snippets","text":"<p>There is a section that holds small code snippets.</p> <p>See also some Bash source code excerpts.</p>","tags":["bash","shell","linux","scripting"]},{"location":"#how-to","title":"How to","text":"<p>Doing specific tasks: concepts, methods, ideas:</p> <ul> <li>Simple locking (against parallel run.md)</li> <li>Rudimentary config files for your scripts</li> <li>Editing files with ed</li> <li>Collapsing Functions</li> <li>Illustrated Redirection Tutorial</li> <li>Calculate with dc</li> <li>Introduction to pax - the POSIX archiver</li> <li>getopts_tutorial (under construction!)</li> <li>dissectabadoneliner An example of a bad oneliner, breakdown and fix (by <code>kojoro</code>)</li> <li>Write tests for ./your-script.sh by using bashtest util</li> </ul>","tags":["bash","shell","linux","scripting"]},{"location":"#bash-syntax-and-operations","title":"Bash syntax and operations","text":"<ul> <li>Bash features overview by version</li> <li>Basic grammar rules</li> <li>Quoting and character escaping</li> <li>Parsing and execution</li> <li>Some words about words...</li> <li>Patterns and pattern matching</li> <li>Arithmetic expressions</li> <li>List of shell options</li> <li>Redirection</li> <li>Special parameters and shell variables</li> <li>Arrays</li> </ul>","tags":["bash","shell","linux","scripting"]},{"location":"#compound-commands","title":"Compound commands","text":"Compound commands overview Grouping <code>{ ...; }</code> command grouping <code>( ... )</code> command grouping in a subshell Conditionals <code>[[ ... ]]</code> conditional expression <code>if ...; then ...; fi</code> conditional branching <code>case ... esac</code> pattern-based branching Loops <code>for word in ...; do ...; done</code> classic for-loop <code>for ((x=1; x&lt;=10; x++)); do ...; done</code> C-style for-loop <code>while ...; do ...; done</code> while loop <code>until ...; do ...; done</code> until loop Misc <code>(( ... ))</code> arithmetic evaluation <code>select word in ...; do ...; done</code> user selections","tags":["bash","shell","linux","scripting"]},{"location":"#expansions-and-substitutions","title":"Expansions and substitutions","text":"Introduction to expansions and substitutions <code>{A,B,C} {A..C}</code> Brace expansion <code>~/ ~root/</code> Tilde expansion <code>$FOO ${BAR%.mp3}</code> Parameter expansion <code>`command` $(command)</code> Command substitution <code>&lt;(command.md) &gt;(command)</code> Process substitution <code>$((1 + 2 + 3)) $[4 + 5 + 6]</code> Arithmetic expansion <code>Hello &lt;---&gt; Word!</code> Word splitting <code>/data/*-av/*.mp?</code> Pathname expansion","tags":["bash","shell","linux","scripting"]},{"location":"#builtin-commands","title":"Builtin Commands","text":"<p>This is a selection of builtin commands and command-like keywords, loosely arranged by their common uses. These are provided directly by the shell, rather than invoked as standalone external commands.</p>","tags":["bash","shell","linux","scripting"]},{"location":"#declaration-commands","title":"Declaration commands","text":"<p>Note</p> <p>Commands that set and query attributes/types, and manipulate simple datastructures.</p> Command Description Alt Type declare Display or set shell variables or functions along with attributes. <code>typeset</code> builtin export Display or set shell variables, also giving them the export attribute. <code>typeset -x</code> special builtin eval Evaluate arguments as shell code. special builtin local Declare variables as having function local scope. builtin readonly Mark variables or functions as read-only. <code>typeset -r</code> special builtin unset Unset variables and functions. special builtin shift Shift positional parameters special builtin","tags":["bash","shell","linux","scripting"]},{"location":"#io","title":"IO","text":"<p>Note</p> <p>Commands for reading/parsing input, or producing/formatting output of standard streams.</p> Command Description Alt Type coproc Co-processes: Run a command in the background with pipes for reading / writing its standard streams. keyword echo Create output from arguments. builtin mapfile Read lines of input into an array. <code>readarray</code> builtin printf \"advanced <code>echo</code>\" builtin read Read input into variables or arrays, or split strings into fields using delimiters. builtin","tags":["bash","shell","linux","scripting"]},{"location":"#configuration-and-debugging","title":"Configuration and Debugging","text":"<p>Note</p> <p>Commands that modify shell behavior, change special options, assist in debugging.</p> Command Description Alt Type caller Identify/print execution frames. builtin set Set the positional parameters and/or set options that affect shell behaviour. special builtin shopt set/get some bash-specific shell options. builtin","tags":["bash","shell","linux","scripting"]},{"location":"#control-flow-and-data-processing","title":"Control flow and data processing","text":"<p>Note</p> <p>Commands that operate on data and/or affect control flow.</p> Command Description Alt Type <code>colon</code> \"true\" null command. <code>true</code> special builtin <code>.</code> (dot) Source external files. <code>source</code> special builtin <code>false</code> Fail at doing nothing. builtin <code>continue / break</code> continue with or break out of loops. special builtin let Arithmetic evaluation simple command. builtin return Return from a function with a specified exit status. special builtin [] The classic <code>test</code> simple command. <code>test</code> builtin","tags":["bash","shell","linux","scripting"]},{"location":"#process-and-job-control","title":"Process and Job control","text":"<p>Note</p> <p>Commands related to jobs, signals, process groups, subshells.</p> Command Description Alt Type exec Replace the current shell process or set redirections. special builtin exit Exit the shell. special builtin trap Set signal handlers or output the current handlers. special builtin kill Send a signal to specified process(es.md) builtin <code>times</code> Display process times. special builtin wait Wait for background jobs and asynchronous lists. builtin","tags":["bash","shell","linux","scripting"]},{"location":"#dictionary","title":"Dictionary","text":"<p>A list of expressions, words, and their meanings can be found under the Dict tab.</p>","tags":["bash","shell","linux","scripting"]},{"location":"#links","title":"Links","text":"","tags":["bash","shell","linux","scripting"]},{"location":"#official-bash-links","title":"Official Bash links","text":"<ul> <li>Chet Ramey's Bash page and its FAQ.</li> <li>GNU Bash software page</li> <li>Official Bash mailing lists:</li> <li>Bug reports: bug-bash@gnu.org (archives)</li> <li>General questions: help-bash@gnu.org (archives)</li> <li>Official Bash git repository:</li> <li>Browse: cgit</li> <li>Clone: <code>git clone git.sv.gnu.org/srv/git/bash.git</code></li> </ul>","tags":["bash","shell","linux","scripting"]},{"location":"#recommended-shell-resources","title":"Recommended Shell resources","text":"<ul> <li>Greg's wiki - Greg Wooledge's (aka \"greycat\") wiki -- with MASSIVE information about Bash and UNIX\u00ae in general.</li> <li>BashFAQ \u2022 BashGuide \u2022 BashPitfalls \u2022 BashSheet</li> <li>Sven Mascheck's pages - A goldmine of information. A must-read.</li> <li>#ksh channel page - #ksh Freenode channel page maintains a solid collection of recommended links.</li> <li>The Grymoire Unix pages - Good scripting information, especially read the quoting guide.</li> <li>Heiner's \"Shell Dorado\" - Tips, tricks, links - for every situation.</li> <li>The Single Unix Specification (version 4, aka POSIX-2008)</li> <li>The Austin Group - List archives, Bug tracker</li> <li>comp.unix.shell FAQ</li> <li>Advanced Bash-Scripting Guide - last update: 10 Mar 2014, but still very useful guide.</li> </ul>","tags":["bash","shell","linux","scripting"]},{"location":"#documentation-reference","title":"Documentation / Reference","text":"<ul> <li>Bash: man page, info page</li> <li>AT&amp;T ksh: ksh88, ksh93</li> <li>mksh (pdksh successor)</li> <li>zsh</li> <li>dash</li> <li>Heirloom Bourne shell</li> <li>Thompson shell</li> </ul>","tags":["bash","shell","linux","scripting"]},{"location":"#assorted-interesting-links","title":"Assorted interesting links","text":"<ul> <li>History and development of the traditional Bourne shell family - very interesting and nice to read!</li> <li>Interview with Chet Ramey</li> <li>Interview with Steve Bourne \u2022 Stephen Bourne - BSDCan 2015 keynote</li> <li>Interview with David Korn</li> <li>Kernighan on the Unix pipeline (computerphile video)</li> <li>Linux in general, with some shell related stuff: nixCraft: Linux Tips, Hacks, Tutorials and Ideas</li> <li>Linux tutorials, guides and how-tos: RoseHosting Blog, bash script for installing WordPress and some basic shell commands</li> <li>Bashphorism list from the Bash IRC channel on Freenode</li> <li>Some more or less funny commandline stuff</li> <li>How to Enable SSH on Ubuntu Tutorial</li> <li>How To Make an Awesome Custom Shell with ZSH</li> </ul>","tags":["bash","shell","linux","scripting"]},{"location":"#bash-libraries-needs-review","title":"Bash Libraries (needs review)","text":"<ul> <li>An oo-style bash library for bash 4 - provides tools for rapid script development and huge libraries.</li> <li>General purpose shell framework for bash 4 - in development.</li> <li>General purpose bash library for bash 4 - active development</li> </ul>","tags":["bash","shell","linux","scripting"]},{"location":"#contact","title":"Contact","text":"<p>Visit us in ircs://irc.libera.chat:6697, channel <code>#bash</code> ;-)</p> <p>If you have critiques or suggestions, please feel free to send a mail using the contact form on the right. Note that there is a simple discussion option below every article.</p> <p>Please also see the imprint if you have problems with the site and its contents (legality, ...)!</p> <p>It also would be nice to drop a line when</p> <ul> <li>it helped you</li> <li>it didn't help you (something missing / unclear)</li> <li>you like it</li> <li>you don't like it</li> <li>you found mistakes / bugs</li> </ul> <p>Simply: Reader's feedback.</p>","tags":["bash","shell","linux","scripting"]},{"location":"bash4/","title":"Bash 4 - a rough overview","text":"<p>Attention</p> <p>Since Bash 4 has been around for quite some time now (4.3 will come soon), I consider it to be \"standard\". This page is not maintained anymore and is left here to keep your links working. See the bashchanges page for new stuff introduced.</p> <p>Besides many bugfixes since Bash 3.2, Bash 4 will bring some interesting new features for shell users and scripters. See also bashchanges for a small general overview with more details.</p> <p>Not all of the changes and news are included here, just the biggest or most interesting ones. The changes to completion, and the readline component are not covered. Though, if you're familiar with these parts of Bash (and Bash 4), feel free to write a chapter here.</p> <p>The complete list of fixes and changes is in the CHANGES or NEWS file of your Bash 4 distribution.</p> <p>The current available stable version is 4.4.18 release (February 03, 2018):</p> <ul> <li>ftp://ftp.cwru.edu/pub/bash/bash-4.4.18.tar.gz</li> <li>ftp://ftp.gnu.org/pub/gnu/bash/bash-4.4.18.tar.gz</li> </ul>"},{"location":"bash4/#new-or-changed-commands-and-keywords","title":"New or changed commands and keywords","text":""},{"location":"bash4/#the-new-coproc-keyword","title":"The new \"coproc\" keyword","text":"<p>Bash 4 introduces the concepts of coprocesses, a well known feature of other shells. The basic concept is simple: It will start any command in the background and set up an array that is populated with accessible files that represent the filedescriptors of the started process.</p> <p>In other words: It lets you start a process in background and communicate with its input and output data streams.</p> <p>See The coproc keyword</p>"},{"location":"bash4/#the-new-mapfile-builtin","title":"The new \"mapfile\" builtin","text":"<p>The <code>mapfile</code> builtin is able to map the lines of a file directly into an array. This avoids having to fill an array yourself using a loop. It enables you to define the range of lines to read, and optionally call a callback, for example to display a progress bar.</p> <p>See: mapfile</p>"},{"location":"bash4/#changes-to-the-case-keyword","title":"Changes to the \"case\" keyword","text":"<p>The <code>case</code> construct understands two new action list terminators:</p> <p>The <code>;&amp;</code> terminator causes execution to continue with the next action list (rather than terminate the <code>case</code> construct).</p> <p>The <code>;;&amp;</code> terminator causes the <code>case</code> construct to test the next given pattern instead of terminating the whole execution.</p> <p>See case</p>"},{"location":"bash4/#changes-to-the-declare-builtin","title":"Changes to the \"declare\" builtin","text":"<p>The <code>-p</code> option now prints all attributes and values of declared variables (or functions, when used with <code>-f</code>). The output is fully re-usable as input.</p> <p>The new option <code>-l</code> declares a variable in a way that the content is converted to lowercase on assignment. For uppercase, the same applies to <code>-u</code>. The option <code>-c</code> causes the content to be capitalized before assignment.</p> <p><code>declare -A</code> declares associative arrays (see below).</p>"},{"location":"bash4/#changes-to-the-read-builtin","title":"Changes to the \"read\" builtin","text":"<p>The <code>read</code> builtin command has some interesting new features.</p> <p>The <code>-t</code> option to specify a timeout value has been slightly tuned. It now accepts fractional values and the special value 0 (zero). When <code>-t 0</code> is specified, <code>read</code> immediately returns with an exit status indicating if there's data waiting or not. However, when a timeout is given, and the <code>read</code> builtin times out, any partial data recieved up to the timeout is stored in the given variable, rather than lost. When a timeout is hit, <code>read</code> exits with a code greater than 128.</p> <p>A new option, <code>-i</code>, was introduced to be able to preload the input buffer with some text (when Readline is used, with <code>-e</code>). The user is able to change the text, or press return to accept it.</p> <p>See read</p>"},{"location":"bash4/#changes-to-the-help-builtin","title":"Changes to the \"help\" builtin","text":"<p>The builtin itself didn't change much, but the data displayed is more structured now. The help texts are in a better format, much easier to read.</p> <p>There are two new options: <code>-d</code> displays the summary of a help text, <code>-m</code> displays a manpage-like format.</p>"},{"location":"bash4/#changes-to-the-ulimit-builtin","title":"Changes to the \"ulimit\" builtin","text":"<p>Besides the use of the 512 bytes blocksize everywhere in POSIX mode, <code>ulimit</code> supports two new limits: <code>-b</code> for max socket buffer size and <code>-T</code> for max number of threads.</p>"},{"location":"bash4/#expansions","title":"Expansions","text":""},{"location":"bash4/#brace-expansion","title":"Brace Expansion","text":"<p>The brace expansion was tuned to provide expansion results with leading zeros when requesting a row of numbers.</p> <p>See brace</p>"},{"location":"bash4/#parameter-expansion","title":"Parameter Expansion","text":"<p>Methods to modify the case on expansion time have been added.</p> <p>On expansion time you can modify the syntax by adding operators to the parameter name.</p> <p>See Case modification on parameter expansion</p>"},{"location":"bash4/#substring-expansion","title":"Substring expansion","text":"<p>When using substring expansion on the positional parameters, a starting index of 0 now causes \\$0 to be prepended to the list (if the positional parameters are used). Before, this expansion started with \\$1:</p> <pre><code># this should display $0 on Bash v4, $1 on Bash v3\necho ${@:0:1}\n</code></pre>"},{"location":"bash4/#globbing","title":"Globbing","text":"<p>There's a new shell option <code>globstar</code>. When enabled, Bash will perform recursive globbing on <code>**</code> \u2013 this means it matches all directories and files from the current position in the filesystem, rather than only the current level.</p> <p>The new shell option <code>dirspell</code> enables spelling corrections on directory names during globbing.</p> <p>See globs</p>"},{"location":"bash4/#associative-arrays","title":"Associative Arrays","text":"<p>Besides the classic method of integer indexed arrays, Bash 4 supports associative arrays.</p> <p>An associative array is an array indexed by an arbitrary string, something like</p> <pre><code>declare -A ASSOC\n\nASSOC[First]=\"first element\"\nASSOC[Hello]=\"second element\"\nASSOC[Peter Pan]=\"A weird guy\"\n</code></pre> <p>See arrays</p>"},{"location":"bash4/#redirection","title":"Redirection","text":"<p>There is a new <code>&amp;&gt;&gt;</code> redirection operator, which appends the standard output and standard error to the named file. This is the same as the good old <code>&gt;&gt;FILE 2&gt;&amp;1</code> notation.</p> <p>The parser now understands <code>|&amp;</code> as a synonym for <code>2&gt;&amp;1 |</code>, which redirects the standard error for a command through a pipe.</p> <p>See redirection</p>"},{"location":"bash4/#interesting-new-shell-variables","title":"Interesting new shell variables","text":"Variable Description BASHPID contains the PID of the current shell (this is different than what <code>$$</code> does!) PROMPT_DIRTRIM specifies the max. level of unshortened pathname elements in the prompt FUNCNEST control the maximum number of shell function recursions <p>See shellvars</p>"},{"location":"bash4/#interesting-new-shell-options","title":"Interesting new Shell Options","text":"<p>The mentioned shell options are off by default unless otherwise mentioned.</p> Option Description <code>checkjobs</code> check for and report any running jobs at shell exit <code>compat*</code> set compatiblity modes for older shell versions (influences regular expression matching in <code>[[ ... ]]</code> <code>dirspell</code> enables spelling corrections on directory names during globbing <code>globstar</code> enables recursive globbing with <code>**</code> <code>lastpipe</code> (4.2) to execute the last command in a pipeline in the current environment <p>See shell_options</p>"},{"location":"bash4/#misc","title":"Misc","text":"<ul> <li>If a command is not found, the shell attempts to execute a shell function named <code>command_not_found_handle</code>, supplying the command words as the function arguments. This can be used to display userfriendly messages or perform different command searches</li> <li>The behaviour of the <code>set -e</code> (<code>errexit</code>) mode was changed, it now acts more intuitive (and is better documented in the manpage).</li> <li>The output target for the <code>xtrace</code> (<code>set -x</code>/<code>set +x</code>) feature is configurable since Bash 4.1 (previously, it was fixed to <code>stderr</code>): a variable named BASH_XTRACEFD can be set to the filedescriptor that should get the output</li> <li>Bash 4.1 is able to log the history to syslog (only to be enabled at compile time in <code>config-top.h</code>)</li> </ul>"},{"location":"commands/classictest/","title":"The classic test command","text":"<p><code>test &lt;EXPRESSION&gt;</code></p> <p><code>[ &lt;EXPRESSION&gt; ]</code></p>"},{"location":"commands/classictest/#general-syntax","title":"General syntax","text":"<p>This command allows you to do various tests and sets its exit code to 0 (<code>true</code>) or 1 (<code>false</code>) whenever such a test succeeds or not. Using this exit code, it's possible to let Bash react on the result of such a test, here by using the command in an if-statement:</p> <pre><code>#!/bin/bash\n\n# test if /etc/passwd exists\nif test -e /etc/passwd; then\n echo \"Alright man...\" &gt;&amp;2\nelse\n echo \"Yuck! Where is it??\" &gt;&amp;2\n exit 1\nfi\n</code></pre> <p>The syntax of the test command is relatively easy. Usually it's the command name <code>test</code> followed by a test type (here <code>-e</code> for \"file exists\") followed by test-type-specific values (here the filename to check, <code>/etc/passwd</code>).</p> <p>There's a second standardized command that does exactly the same: the command <code>[</code> \u2013 the difference just is that it's called <code>[</code> and the last argument to the command must be a <code>]</code>: It forms <code>[ &lt;EXPRESSION&gt; ]</code>.</p> <p>Let's rewrite the above example to use it:</p> <pre><code>#!/bin/bash\n\n# test if /etc/passwd exists\nif [ -e /etc/passwd ]; then\n echo \"Alright man...\" &gt;&amp;2\nelse\n echo \"Yuck! Where is it??\" &gt;&amp;2\n exit 1\nfi\n</code></pre> <p>One might think now that these <code>[</code> and <code>]</code> belong to the syntax of Bash's if-clause: No they don't! It's a simple, ordinary command, still!</p> <p>Another thing you have to remember is that if the test command wants one parameter for a test, you have to give it one parameter. Let's check for some of your music files:</p> <pre><code>#!/bin/bash\n\nmymusic=\"/data/music/Van Halen/Van Halen - Right Now.mp3\"\n\nif [ -e \"$mymusic\" ]; then\n echo \"Let's rock\" &gt;&amp;2\nelse\n echo \"No music today, sorry...\" &gt;&amp;2\n exit 1\nfi\n</code></pre> <p>As you definitely noted, the filename contains spaces. Since we call a normal ordinary command (<code>test</code> or <code>[</code>) the shell will word-split the expansion of the variable <code>mymusic</code>: You need to quote it when you don't want the <code>test</code>-command to complain about too many arguments for this test-type! If you didn't understand it, please read the article about words....</p> <p>Please also note that the file-tests want one filename to test. Don't give a glob (filename-wildcards) as it can expand to many filenames =&gt; too many arguments!</p> <p>Another common mistake is to provide too few arguments:</p> <pre><code>[ \"$mystring\"!=\"test\" ]\n</code></pre> <p>This provides exactly one test-argument to the command. With one parameter, it defaults to the <code>-n</code> test: It tests if a provided string is empty (<code>FALSE</code>) or not (<code>TRUE</code>) - due to the lack of spaces to separate the arguments the shown command always ends <code>TRUE</code>!</p> <p>Well, I addressed several basic rules, now let's see what the test-command can do for you. The Bash test-types can be split into several sections: file tests, string tests, arithmetic tests, misc tests. Below, the tests marked with are non-standard tests (i.e. not in SUS/POSIX/etc..).</p>"},{"location":"commands/classictest/#file-tests","title":"File tests","text":"<p>This section probably holds the most tests, I'll list them in some logical order. Since Bash 4.1, all tests related to permissions respect ACLs, if the underlying filesystem/OS supports them.</p> Operator syntax Description -a True if exists. (not recommended, may collide with <code>-a</code> for <code>AND</code>, see below) -e True if exists. -f True, if exists and is a regular file. -d True, if exists and is a directory. -c True, if exists and is a character special file. -b True, if exists and is a block special file. -p True, if exists and is a named pipe (FIFO). -S True, if exists and is a socket file. -L True, if exists and is a symbolic link. -h True, if exists and is a symbolic link. -g True, if exists and has sgid bit set. -u True, if exists and has suid bit set. -r True, if exists and is readable. -w True, if exists and is writable. -x True, if exists and is executable. -s True, if exists and has size bigger than 0 (not empty). -t True, if file descriptor is open and refers to a terminal. -nt True, if is newer than (mtime). -ot True, if is older than (mtime). -ef True, if and refer to the same device and inode numbers."},{"location":"commands/classictest/#string-tests","title":"String tests","text":"Operator syntax Description -z True, if is empty. -n True, if is not empty (this is the default operation). = True, if the strings are equal. != True, if the strings are not equal. &lt; True if sorts before lexicographically (pure ASCII, not current locale!). Remember to escape! Use <code>&lt;</code> &gt; True if sorts after lexicographically (pure ASCII, not current locale!). Remember to escape! Use <code>&gt;</code>"},{"location":"commands/classictest/#arithmetic-tests","title":"Arithmetic tests","text":"Operator syntax Description -eq True, if the integers are equal. -ne True, if the integers are NOT equal. -le True, if the first integer is less than or equal second one. -ge True, if the first integer is greater than or equal second one. -lt True, if the first integer is less than second one. -gt True, if the first integer is greater than second one."},{"location":"commands/classictest/#misc-syntax","title":"Misc syntax","text":"Operator syntax Description -a True, if and are true (AND). Note that <code>-a</code> also may be used as a file test (see above) -o True, if either or is true (OR). ! True, if is false (NOT). ( ) Group a test (for precedence). Attention: In normal shell-usage, the <code>(</code> and <code>)</code> must be escaped; use <code>(</code> and <code>)</code>! -o True, if the shell option is set. -v True if the variable has been set. Use <code>var[n]</code> for array elements. -R True if the variable has been set and is a nameref variable (since 4.3-alpha)"},{"location":"commands/classictest/#number-of-arguments-rules","title":"Number of Arguments Rules","text":"<p>The <code>test</code> builtin, especially hidden under its <code>[</code> name, may seem simple but is in fact causing a lot of trouble sometimes. One of the difficulty is that the behaviour of <code>test</code> not only depends on its arguments but also on the number of its arguments.</p> <p>Here are the rules taken from the manual:</p> <p>Note</p> <p>This is for the command <code>test</code>, for <code>[</code> the number of arguments is calculated without the final <code>]</code>, for example <code>[ ]</code> follows the \"zero arguments\" rule.</p> <ul> <li>0 arguments<ul> <li>The expression is false.</li> </ul> </li> <li>1 argument<ul> <li>The expression is true if, and only if, the argument is not null</li> </ul> </li> <li>2 arguments<ul> <li>If the first argument is <code>!</code> (exclamation mark), the expression is true if, and only if, the second argument is null</li> <li>If the first argument is one of the unary conditional operators listed above under the syntax rules, the expression is true if the unary test is true</li> <li>If the first argument is not a valid unary conditional operator, the expression is false</li> </ul> </li> <li>3 arguments<ul> <li>If the second argument is one of the binary conditional operators listed above under the syntax rules, the result of the expression is the result of the binary test using the first and third arguments as operands</li> <li>If the first argument is <code>!</code>, the value is the negation of the two-argument test using the second and third arguments</li> <li>If the first argument is exactly <code>(</code> and the third argument is exactly <code>)</code>, the result is the one-argument test of the second argument. Otherwise, the expression is false. The <code>-a</code> and <code>-o</code> operators are considered binary operators in this case (Attention: This means the operator <code>-a</code> is not a file operator in this case!)</li> </ul> </li> <li>4 arguments<ul> <li>If the first argument is <code>!</code>, the result is the negation of the three-argument expression composed of the remaining arguments. Otherwise, the expression is parsed and evaluated according to precedence using the rules listed above</li> </ul> </li> <li>5 or more arguments<ul> <li>The expression is parsed and evaluated according to precedence using the rules listed above</li> </ul> </li> </ul> <p>These rules may seem complex, but it's not so bad in practice. Knowing them might help you to explain some of the \"unexplicable\" behaviours you might encounter:</p> <pre><code>var=\"\"\nif [ -n $var ]; then echo \"var is not empty\"; fi\n</code></pre> <p>This code prints \"var is not empty\", even though <code>-n something</code> is supposed to be true if <code>$var</code> is not empty - why?</p> <p>Here, as <code>$var</code> is not quoted, word splitting occurs and <code>$var</code> results in actually nothing (Bash removes it from the command's argument list!). So the test is in fact <code>[ -n ]</code> and falls into the \"one argument\" rule, the only argument is \"-n\" which is not null and so the test returns true. The solution, as usual, is to quote the parameter expansion: <code>[ -n \"$var\" ]</code> so that the test has always 2 arguments, even if the second one is the null string.</p> <p>These rules also explain why, for instance, -a and -o can have several meanings.</p>"},{"location":"commands/classictest/#and-and-or","title":"AND and OR","text":""},{"location":"commands/classictest/#the-prefered-way","title":"The Prefered Way","text":"<p>The way often recommended to logically connect several tests with AND and OR is to use several single test commands and to combine them with the shell <code>&amp;&amp;</code> and <code>||</code> list control operators.</p> <p>See this:</p> <pre><code>if [ -n \"$var\"] &amp;&amp; [ -e \"$var\"]; then\n echo \"\\$var is not null and a file named $var exists!\"\nfi\n</code></pre> <p>The return status of AND and OR lists is the exit status of the last command executed in the list</p> <ul> <li>With <code>command1 &amp;&amp; command2</code>, <code>command2</code> is executed if, and only if, <code>command1</code> returns an exit status of zero (true)</li> <li>With <code>command1 \u2502\u2502 command2</code>, <code>command2</code> is executed if, and only if, <code>command1</code> returns a non-zero exit status (false)</li> </ul>"},{"location":"commands/classictest/#the-other-way-a-and-o","title":"The other way: -a and -o","text":"<p>The logical operators AND and OR for the test-command itself are <code>-a</code> and <code>-o</code>, thus:</p> <pre><code>if [ -n \"$var\" -a -e \"$var\" ] ; then\n echo \"\\$var is not null and a file named $var exists\"\nfi\n</code></pre> <p>They are not <code>&amp;&amp;</code> or <code>||</code>:</p> <pre><code>$ if [ -n \"/tmp\" &amp;&amp; -d \"/tmp\"]; then echo true; fi # DOES NOT WORK\nbash: [: missing `]'\n</code></pre> <p>You might find the error message confusing, <code>[</code> does not find the required final <code>]</code>, because as seen above <code>&amp;&amp;</code> is used to write a list of commands. The <code>if</code> statement actually sees two commands:</p> <ul> <li><code>[ -n \"/tmp\"</code></li> <li><code>-d \"/tmp\" ]</code></li> </ul> <p>...which must fail.</p>"},{"location":"commands/classictest/#why-you-should-avoid-using-a-and-o","title":"Why you should avoid using -a and -o","text":""},{"location":"commands/classictest/#if-portability-is-a-concern","title":"If portability is a concern","text":"<p>POSIX\u00ae/SUSv3 does not specify the behaviour of <code>test</code> in cases where there are more than 4 arguments. If you write a script that might not be executed by Bash, the behaviour might be different! <sup>1</sup></p>"},{"location":"commands/classictest/#if-you-want-the-cut-behaviour","title":"If you want the cut behaviour","text":"<p>Let's say, we want to check the following two things (AND):</p> <ol> <li>if a string is null (empty)</li> <li>if a command produced an output</li> </ol> <p>Let's see:</p> <pre><code>if [ -z \"false\" -a -z \"$(echo I am executed &gt;&amp;2)\" ] ; then ... \n</code></pre> <p>=&gt; The arguments are all expanded before <code>test</code> runs, thus the echo-command is executed.</p> <pre><code>if [ -z \"false\" ] &amp;&amp; [ -z \"$(echo I am not executed &gt;&amp;2)\" ]; then... \n</code></pre> <p>=&gt; Due to the nature of the <code>&amp;&amp;</code> list operator, the second test-command runs only if the first test-command returns true, our echo-command is not executed.</p> <p>Note</p> <p>In my opinion, <code>-a</code> and <code>-o</code> are also less readable <code>[pgas]</code></p>"},{"location":"commands/classictest/#precedence-and-parenthesis","title":"Precedence and Parenthesis","text":"<p>Take care if you convert your scripts from using <code>-a</code> and <code>-o</code> to use the list way (<code>&amp;&amp;</code> and <code>||</code>):</p> <ul> <li>in the test-command rules, <code>-a</code> has precedence over <code>-o</code></li> <li>in the shell grammar rules, <code>&amp;&amp;</code> and <code>||</code> have equal precedence</li> </ul> <p>That means, you can get different results, depending on the manner of use:</p> <pre><code>$ if [ \"true\" ] || [ -e /does/not/exist ] &amp;&amp; [ -e /does/not/exist ]; then echo true; else echo false; fi\nfalse\n\n$ if [ \"true\" -o -e /does/not/exist -a -e /does/not/exist ]; then echo true; else echo false;fi\ntrue\n</code></pre> <p>As a result you have to think about it a little or add precedence control (parenthesis).</p> <p>For <code>&amp;&amp;</code> and <code>||</code> parenthesis means (shell-ly) grouping the commands, and since <code>( ... )</code> introduces a subshell we will use <code>{ ... }</code> instead:</p> <pre><code>$ if [ \"true\" ] || { [ -e /does/not/exist ] &amp;&amp; [ -e /does/not/exist ] ;} ; then echo true; else echo false; fi\ntrue\n</code></pre> <p>For the test command, the precedence parenthesis are, as well, <code>( )</code>, but you need to escape or quote them, so that the shell doesn't try to interpret them:</p> <pre><code>$ if [ ( \"true\" -o -e /does/not/exist ) -a -e /does/not/exist ]; then echo true; else echo false; fi\nfalse\n\n# equivalent, but less readable IMHO:\n$ if [ '(' \"true\" -o -e /does/not/exist ')' -a -e /does/not/exist ]; then echo true; else echo false; fi\nfalse\n</code></pre>"},{"location":"commands/classictest/#not","title":"NOT","text":"<p>As for AND and OR, there are 2 ways to negate a test with the shell keyword <code>!</code> or passing <code>!</code> as an argument to <code>test</code>.</p> <p>Here <code>!</code> negates the exit status of the command <code>test</code> which is 0 (true), and the else part is executed:</p> <pre><code>if ! [ -d '/tmp' ]; then echo \"/tmp doesn't exists\"; else echo \"/tmp exists\"; fi\n</code></pre> <p>Here the <code>test</code> command itself exits with status 1 (false) and the else is also executed:</p> <pre><code>if [ ! -d '/tmp' ]; then echo \"/tmp doesn't exists\"; else echo \"/tmp exists\"; fi\n</code></pre> <p>Unlike for AND and OR, both methods for NOT have an identical behaviour, at least for doing one single test.</p>"},{"location":"commands/classictest/#pitfalls-summarized","title":"Pitfalls summarized","text":"<p>In this section you will get all the mentioned (and maybe more) possible pitfalls and problems in a summary.</p>"},{"location":"commands/classictest/#general","title":"General","text":"<p>Here's the copy of a mail on bug-bash list. A user asking a question about using the test command in Bash, he's talking about a problem, which you may have already had yourself:</p> <pre><code>From: (PROTECTED)\nSubject: -d option not working. . .?\nDate: Tue, 11 Sep 2007 21:51:59 -0400\nTo: bug-bash@gnu.org\n\nHi All,\n\nI've got a script that I'm trying to set up, but it keeps telling me \nthat \"[-d command not found\". Can someone please explain what is \nwrong with this?:\n\n\n\n\n#!/bin/sh\n\nfor i in $*\ndo\n{\n if [-d $i]\n then\n echo \"$i is a directory! Yay!\"\n else\n echo \"$i is not a directory!\"\n fi\n}\ndone\n\nRegards\n</code></pre> <p>See the problem regarding the used test-command (the other potential problems are not of interest here)?</p> <pre><code>[-d $i]\n</code></pre> <p>He simply didn't know that <code>test</code> or <code>[</code> is a normal, simple command. Well, here's the answer he got. I quote it here, because it's a well written text that addresses most of the common issues with the \"classic\" test command:</p> <pre><code>From: Bob Proulx (EMAIL PROTECTED)\nSubject: Re: -d option not working. . .?\nDate: Wed, 12 Sep 2007 10:32:35 -0600\nTo: bug-bash@gnu.org\n\n&gt; (QUOTED TEXT WAS REMOVED)\n\nThe shell is first and foremost a way to launch other commands. The\nsyntax is simply \"if\" followed by a command-list, (e.g. if /some/foo;\nor even if cmd1; cmd2; cmd3; then). Plus the '( ... )' syntax is\nalready taken by the use of starting a subshell.\n\nAs I recall in the original shell language the file test operator was\nnot built-in. It was provided by the standalone '/bin/test' command.\nThe result was effectively this:\n\n if /bin/test -d somedir\n\nAlthough the full path /bin/test was never used. I showed it that way\nhere for emphasis that following the 'if' statement is a command list.\nNormally it would simply have been:\n\n if test -d somedir\n\nOf course that is fine and for the best portability that style is\nstill the recommended way today to use the test command. But many\npeople find that it looks different from other programming languages.\nTo make the test operator (note I mention the test operator and not\nthe shell language, this is a localized change not affecting the\nlanguage as a whole) look more like other programming languages the\n'test' program was coded to ignore the last argument if it was a ']'.\nThen a copy of the test program could be used as the '[' program.\n\n ...modify /bin/test to ignore ']' as last argument...\n cp /bin/test /bin/[\n\nThis allows:\n\n if [ -d somedir ]\n\nDoesn't that look more normal? People liked it and it caught on. It\nwas so popular that both 'test' and '[' are now shell built-ins. They\ndon't launch an external '/bin/test' program anymore. But they *used*\nto launch external programs. Therefore argument parsing is the same\nas if they still did launch an external program. This affects\nargument parsing.\n\n it test -f *.txt\n test: too many arguments\n\nOops. I have twenty .txt files and so test got one -f followed by the\nfirst file followed by the remaining files. (e.g. test -f 1.txt 2.txt\n3.txt 4.txt)\n\n if test -d $file\n test: argument expected\n\nOops. I meant to set file.\n\n file=/path/some/file\n if test -d $file\n\nIf variables such as that are not set then they wlll be expanded by\nthe shell before passing them to the (possibly external) command and\ndisappear entirely. This is why test arguments should always be quoted.\n\n if test -d \"$file\"\n if [ -d \"$file\" ]\n\nActually today test is defined that if only one argument is given as\nin this case \"test FOO\" then then test returns true if the argument is\nnon-zero in text length. Because \"-d\" is non-zero length \"test -d\" is\ntrue. The number of arguments affects how test parses the args. This\navoids a case where depending upon the data may look like a test\noperator.\n\n DATA=\"something\"\n if test \"$DATA\" # true, $DATA is non-zero length\n\n DATA=\"\"\n if test \"$DATA\" # false, $DATA is zero length\n\nBut the problem case is how should test handle an argument that looks\nlike an operator? This used to generate errors but now because it is\nonly one argument is defined to be the same as test -n $DATA.\n\n DATA=\"-d\"\n if test \"$DATA\" # true, $DATA is non-zero length\n if test -d # true, same as previous case.\n\nBecause test and [ are possibly external commands all of the parts of\nthem are chosen to avoid shell metacharacters. The Fortran operator\nnaming was well known at the time (e.g. .gt., .eq., etc.) and was\npressed into service for the shell test operator too. Comming from\nFortran using -gt, -eq, etc. looked very normal.\n\nIncorrect use generating unlikely to be intended results:\n\n if test 5 &gt; 2 # true, \"5\" is non-zero length, creates file named \"2\"\n\nIntended use:\n\n if test 5 -gt 2 # true (and no shell meta characters needing quoting)\n\nThen much later, sometime in the mid 1980's, the Korn sh decided to\nimprove upon this situation. A new test operator was introduced.\nThis one was always a shell built-in and therefore could act upon the\nshell arguments directly. This is '[[' which is a shell keyword.\n(Keyword, metacharacters, builtins, all are different.) Because the\nshell processes [[ internally all arguments are known and do not need\nto be quoted.\n\n if [[ -d $file ]] # okay\n if [[ 5 &gt; 2 ]] # okay\n\nI am sure that I am remembering a detail wrong but hopefully this is\nuseful as a gentle introduction and interesting anyway.\n\nBob\n</code></pre> <p>I hope this text protects you a bit from stepping from one pitfall into the next.</p> <p>I find it very interesting and informative, that's why I quoted it here. Many thanks, Bob, also for the permission to copy the text here!</p>"},{"location":"commands/classictest/#code-examples","title":"Code examples","text":""},{"location":"commands/classictest/#snipplets","title":"Snipplets","text":"<p>Some code snipplets follow, different ways of shell reaction is used.</p> <ul> <li>check if a variable is defined/non-NULL<ul> <li><code>test \"$MYVAR\"</code></li> <li><code>[ \"$MYVAR\" ]</code></li> <li>Note: There are possibilities to make a difference if a variable is undefined or NULL - see Parameter Expansion - Using an alternate value</li> </ul> </li> <li>check if a directory exists, if not, create it<ul> <li><code>test ! -d /home/user/foo &amp;&amp; mkdir /home/user/foo</code></li> <li><code>[ ! -d /home/user/foo ] &amp;&amp; mkdir /home/user/foo</code></li> <li><code>if [ ! -d /home/user/foo ]; then mkdir /home/user/foo; fi</code></li> </ul> </li> <li>check if minimum one parameter was given, and that one is \"Hello\"<ul> <li><code>test $# -ge 1 -a \"$1\" = \"Hello\" || exit 1</code></li> <li><code>[ $# -ge 1 ] &amp;&amp; [ \"$1\" = \"Hello\" ] || exit 1</code> (see lists description)</li> </ul> </li> </ul>"},{"location":"commands/classictest/#listing-directories","title":"Listing directories","text":"<p>Using a for-loop to iterate through all entries of a directory, if an entry is a directory (<code>[ -d \"$fn\" ]</code>), print its name:</p> <pre><code>for fn in *; do\n [ -d \"$fn\" ] &amp;&amp; echo \"$fn\"\ndone\n</code></pre>"},{"location":"commands/classictest/#see-also","title":"See also","text":"<ul> <li>Internal: conditional expression (aka \"the new test command\")</li> <li>Internal: the if-clause</li> </ul> <ol> <li> <p>Of course, one can wonder what is the use of including the parenthesis in the specification without defining the behaviour with more than 4 arguments or how usefull are the examples with 7 or 9 arguments attached to the specification. \u21a9</p> </li> </ol>"},{"location":"commands/builtin/caller/","title":"The caller builtin command","text":""},{"location":"commands/builtin/caller/#synopsis","title":"Synopsis","text":"<pre><code>caller [FRAMENUMBER]\n</code></pre>"},{"location":"commands/builtin/caller/#description","title":"Description","text":"<p>The <code>caller</code> builtin command is used to print execution frames of subroutine calls. Without giving a framenumber, the topmost execution frame information is printed (\"who called me\") wile linenumber and filename.</p> <p>When an execution frame number is given (0 - topmost), the linenumber, the subroutine (function) and the filename is printed. When an invalid execution frame number is given, it exists <code>FALSE</code>. This way it can be used in a loop (see the examples section below).</p>"},{"location":"commands/builtin/caller/#examples","title":"Examples","text":""},{"location":"commands/builtin/caller/#simple-stack-trace","title":"Simple stack trace","text":"<p>The code below defines a function <code>die</code> that is used to exit the program. It prints a list of execution frames, starting with the topmost frame (0). The topmost frame is the \"caller of the die function\", in this case function \"f1\".</p> <p>This way, you can print a \"stack trace\" for debugging or logging purposes.</p> <p>The code is made very simple, just to show the basic purposes.</p> <pre><code>#!/bin/bash\n\ndie() {\n local frame=0\n while caller $frame; do\n ((++frame));\n done\n echo \"$*\"\n exit 1\n}\n\nf1() { die \"*** an error occured ***\"; }\nf2() { f1; }\nf3() { f2; }\n\nf3\n</code></pre> <p>Output</p> <pre><code>12 f1 ./callertest.sh\n13 f2 ./callertest.sh\n14 f3 ./callertest.sh\n16 main ./callertest.sh\n*** an error occured ***\n</code></pre>"},{"location":"commands/builtin/caller/#notes","title":"Notes","text":"<ul> <li><code>caller</code> produces no output unless used within a script that's run from a real file. It isn't particularly useful for interactive use, but can be used to create a decent <code>die</code> function to track down errors in moderately complex scripts. <code>{ bash /dev/stdin; } &lt;&lt;&lt;$'f(){ g; }\\ng(){ h; }\\nh(){ while caller $((n++)); do :; done; }\\nf'</code></li> <li>For more sophisticated debugging, Bash extended debugging features are available and a number of special parameters that give more detail than caller (e.g. BASH_ARG{C,V}). Tools such as Bashdb can assist in using some of Bash's more advanced debug features.</li> <li>The Bash manpage and help text specifies that the argument to <code>caller</code> is an \"expr\" (whatever that means). Only an integer is actually allowed, with no special interpretation of an \"expression\" as far as we can tell.</li> </ul>"},{"location":"commands/builtin/caller/#portability-considerations","title":"Portability considerations","text":"<ul> <li><code>caller</code> is not specified by POSIX(R)</li> <li>the <code>caller</code> builtin command appeared in Bash version 3.0</li> </ul>"},{"location":"commands/builtin/caller/#see-also","title":"See also","text":""},{"location":"commands/builtin/cd/","title":"The cd builtin command","text":""},{"location":"commands/builtin/cd/#synopsis","title":"Synopsis","text":"<pre><code>cd [-L|-P] [DIRECTORY]\n\ncd -\n</code></pre>"},{"location":"commands/builtin/cd/#description","title":"Description","text":"<p>The <code>cd</code> builtin command is used to change the current working directory</p> <ul> <li>to the given directory (<code>cd DIRECTORY</code>)</li> <li>to the previous working directory (<code>cd -</code>) as saved in the OLDPWD shell variable</li> <li>to the user's home directory as specified in the HOME environment variable (when used without a <code>DIRECTORY</code> argument)</li> </ul> <p>The <code>cd</code> builtin command searches the directories listed in CDPATH for a matching directory.</p> <p>The default behaviour is to follow symbolic links unless the <code>-P</code> option is given or the shell is configured to do so (see the <code>-P</code> option of the set builtin command).</p>"},{"location":"commands/builtin/cd/#options","title":"Options","text":"Option Description <code>-L</code> Follow symbolic links (default) <code>-P</code> Do not follow symbolic links <code>-@</code> Browse a file's extended attributed, if supported"},{"location":"commands/builtin/cd/#exit-status","title":"Exit status","text":"<ul> <li>true if the directory was changed successfully</li> <li>false if a change to the home directory was requested, but HOME is unset</li> <li>false if anything else goes wrong</li> </ul>"},{"location":"commands/builtin/cd/#examples","title":"Examples","text":""},{"location":"commands/builtin/cd/#change-the-working-directory-to-the-users-home-directory","title":"Change the working directory to the user's home directory","text":"<pre><code>cd\n</code></pre>"},{"location":"commands/builtin/cd/#change-the-working-directory-to-the-previous-directory","title":"Change the working directory to the previous directory","text":"<pre><code>cd -\n</code></pre>"},{"location":"commands/builtin/cd/#portability-considerations","title":"Portability considerations","text":""},{"location":"commands/builtin/cd/#see-also","title":"See also","text":"<ul> <li>variable CDPATH</li> <li>variable HOME</li> <li>variable OLDPWD</li> <li>the <code>-P</code> option of the set builtin command</li> </ul>"},{"location":"commands/builtin/declare/","title":"The declare builtin command","text":""},{"location":"commands/builtin/declare/#synopsis","title":"Synopsis","text":"<pre><code>declare [-aAfFgilnrtux] [-p] [NAME[=VALUE] ...]\n\n# obsolete typeset synonym\ntypeset [-aAfFgilnrtux] [-p] [NAME[=VALUE] ...]\n</code></pre>"},{"location":"commands/builtin/declare/#description","title":"Description","text":"<p><code>declare</code> is used to display or set variables along with variable attributes. When used to display variables/functions and their value, the output is re-usable as input for the shell.</p> <p>If no <code>NAME</code> is given, it displays the values of all variables or functions when restricted by the <code>-f</code> option.</p> <p>If <code>NAME</code> is followed by <code>=VALUE</code>, <code>declare</code> also sets the value for a variable.</p> <p>When used in a function, <code>declare</code> makes <code>NAMEs</code> local variables, unless used with the <code>-g</code> option.</p> <p>Don't use it's synonym <code>typeset</code> when coding for Bash, since it's tagged as obsolete.</p>"},{"location":"commands/builtin/declare/#options","title":"Options","text":"<p>Below, <code>[-+]X</code> indicates an attribute, use <code>-X</code> to set the attribute, <code>+X</code> to remove it.</p> Option Description <code>[-+]a</code> make NAMEs indexed arrays (removing with <code>+a</code> is valid syntax, but leads to an error message) <code>[-+]A</code> make NAMEs associative arrays <code>[-+]c</code> Undocumented convert NAMEs to \"capcase\" on assignment (makes the first letter upper-case and the rest lower). Requires Bash built with <code>-DCASEMOD_CAPCASE</code> <code>-f</code> restrict action or display to function names and definitions (removing with <code>+f</code> is valid syntax, but leads to an error message) <code>-F</code> restrict display to function names only (plus line number and source file when debugging) <code>-g</code> create global variables when used in a shell function; otherwise ignored (by default, <code>declare</code> declares local scope variables when used in shell functions) <code>[-+]i</code> make NAMEs have the \"integer\" attribute <code>[-+]l</code> convert NAMEs to lower case on assignment (makes sure the variable contains only lower case letters) <code>[-+]n</code> make NAME a reference to the variable named by its value. Introduced in Bash 4.3-alpha. ''<code>${!NAME}</code>'' reveals the reference variable name, VALUE. Use <code>unset -n NAME</code> to unset the variable. (<code>unset -v NAME</code> unsets the VALUE variable.) Use <code>[[ -R NAME ]]</code> to test if NAME has been set to a VALUE, another variable's name. <code>-p</code> display the attributes and value of each NAME <code>[-+]r</code> make NAMEs readonly (removing with <code>+r</code> is valid syntax, but not possible) <code>[-+]t</code> make NAMEs have the \"trace\" attribute (effective only for functions) <code>[-+]u</code> convert NAMEs to upper case on assignment (makes sure the variable contains only upper case letters) <code>[-+]x</code> make NAMEs exported"},{"location":"commands/builtin/declare/#return-status","title":"Return status","text":"Status Reason 0 no error != 0 invalid option != 0 invalid variable name given != 0 attempt to define a function using <code>-f</code> != 0 assignment to a readonly variable != 0 removing the readonly-attribute from a readonly variable != 0 assignment to an array variable without the compound assignment syntax (<code>array=(...)</code>) != 0 attempt to use <code>+a</code> to \"destroy\" an array != 0 attemt to display a non-existent function with <code>-f</code>"},{"location":"commands/builtin/declare/#notes","title":"Notes","text":"<p>Unix shells offer very few datatypes. Bash and some other shells extend this by allowing \"attributes\" to be set on variable names. The only attributes specified by POSIX are <code>export</code> and <code>readonly</code>, which are set by their own dedicated builtins. Datatypes in bash have a few other interesting capabilities such as the ability to modify data on assignment.</p>"},{"location":"commands/builtin/declare/#examples","title":"Examples","text":""},{"location":"commands/builtin/declare/#display-defined-functions","title":"Display defined functions","text":"<p><code>declare -f</code> can be used to display all defined functions...</p> <pre><code>$ declare -f\nfoo ()\n{\n echo \"FOO is BAR\"\n}\nworld ()\n{\n echo \"Hello World!\"\n}\n</code></pre> <p>...or just a specific defined function.</p> <pre><code>$ declare -f foo\nfoo ()\n{\n echo \"FOO is BAR\"\n}\n</code></pre>"},{"location":"commands/builtin/declare/#nameref","title":"Nameref","text":"<p>Bash 4.3 adds a new way to indirectly reference variables. <code>typeset -n</code> or <code>declare -n</code> can be used to make a variable indirectly refer to another. In Bash, the lvalue of the assignment given to <code>typeset -n</code> or <code>declare -n</code> will refer to the variable whose name is expanded on the RHS.</p> <p><code>typeset -n</code> is used in the example below. See notes below.</p> <pre><code># Sum a set of arrays and assign the result indirectly, also printing each intermediary result (without portability workarounds)\n# sum name arrname [ arrname ... ]\nfunction sum {\n typeset -n _result=$1 _arr\n typeset IFS=+\n _result=0\n for _arr in \"${@:2}\"; do # Demonstrate the special property of \"for\" on a nameref.\n (( _result += ${_arr[*]} ))\n printf '%s = %d\\n' \"${!_result}\" \"$_result\" # Demonstrate the special property of ${!ref} on a nameref.\n done\n}\n\na=(1 2 3) b=(6 5 4) c=(2 4 6)\nsum total a b c\nprintf 'Final value of \"total\" is: %d\\n' \"$total\"\n</code></pre> function sum { typeset -n _result=$1 shift typeset IFS=+ _arrx _result=0 for _arrx in \"$@\"; do # Demonstrate the special property of \"for\" on a nameref. typeset -n _arr=$_arrx (( _result += ${_arr[*]} )) printf '%s = %d\\n' \"${!_result}\" \"$_result\" # Demonstrate the special property of ${!ref} on a nameref. done } a=(1 2 3); b=(6 5 4); c=(2 4 6) sum total a b c printf \\'Final value of \\\"total\\\" is: %d\\\\n\\' \\\"\\$total\\\" <p><code>typeset -n</code> is currently implemented in ksh93, mksh, and Bash 4.3. Bash and mksh's implementations are quite similar, but much different from ksh93's. See Portability considerations for details. ksh93 namerefs are much more powerful than Bash's.</p>"},{"location":"commands/builtin/declare/#portability-considerations","title":"Portability considerations","text":"<ul> <li><code>declare</code> is not specified by POSIX\u00ae</li> <li><code>declare</code> is unique to Bash and totally non-portable with the possible exception of Zsh in Bash compatibility mode. Bash marks the synonym <code>typeset</code> as obsolete, which in Bash behaves identically to <code>declare</code>. All other Korn-like shells use <code>typeset</code>, so it probably isn't going away any time soon. Unfortunately, being a non-standard builtin, <code>typeset</code> differs significantly between shells. ksh93 also considers <code>typeset</code> a special builtin, while Bash does not - even in POSIX mode. If you use <code>typeset</code>, you should attempt to only use it in portable ways.</li> <li>todo nameref portability...</li> </ul>"},{"location":"commands/builtin/declare/#see-also","title":"See also","text":"<ul> <li>arrays</li> <li>readonly</li> <li>unset</li> <li>declaration commands will change the behavior of certain builtins such as <code>export</code> in the next version of POSIX.</li> </ul>"},{"location":"commands/builtin/echo/","title":"The echo builtin command","text":""},{"location":"commands/builtin/echo/#synopsis","title":"Synopsis","text":"<pre><code>echo [-neE] [arg ...]\n</code></pre>"},{"location":"commands/builtin/echo/#description","title":"Description","text":"<p><code>echo</code> outputs it's args to stdout, separated by spaces, followed by a newline. The return status is always <code>0</code>. If the shopt option <code>xpg_echo</code> is set, Bash dynamically determines whether echo should expand escape characters (listed below) by default based on the current platform. <code>echo</code> doesn't interpret <code>--</code> as the end of options, and will simply print this string if given.</p>"},{"location":"commands/builtin/echo/#options","title":"Options","text":"Option Description <code>-n</code> The trailing newline is suppressed. <code>-e</code> Interpretation of the following backslash-escaped characters (below) is enabled. <code>-E</code> Disables the interpretation of these escape characters, even on systems where they are interpreted by default."},{"location":"commands/builtin/echo/#escape-sequences","title":"Escape sequences","text":"Escape Description <code>\\a</code> alert (bell) <code>\\b</code> backspace <code>\\c</code> suppress further output <code>\\e</code> <code>\\E</code> an escape character <code>\\f</code> form feed <code>\\n</code> new line <code>\\r</code> carriage return <code>\\t</code> horizontal tab <code>\\v</code> vertical tab <code>\\\\</code> backslash <code>\\0nnn</code> the eight-bit character whose value is the octal value nnn (zero to three octal digits) <code>\\xHH</code> the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) <code>\\uHHHH</code> the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits) <code>\\UHHHHHHHH</code> the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits)"},{"location":"commands/builtin/echo/#examples","title":"Examples","text":""},{"location":"commands/builtin/echo/#portability-considerations","title":"Portability considerations","text":"<ul> <li> <p><code>echo</code> is a portability train wreck. No major shell follows POSIX completely, and any shell that attempts to do so should be considered horribly broken. SUSv4 specifies that <code>echo</code> shall not include any options. Further, it specifies that the behavior of <code>-n</code> as a first argument shall be determined by the implementation, unless XSI is followed, in which case <code>-n</code> is always treated as a string, and backslash escapes are interpreted by default. <code>dash</code> has the misfeature of following this and interpreting escapes by default, but includes a <code>-n</code> feature for suppressing newlines nevertheless.</p> <p>In practice, if you're able to assume a korn-like shell including bash, mksh, or zsh, <code>echo</code> when used in simple cases is generally reliable. For example, in the very common situation in which echo is supplied with a single argument and whose output is to have a newline appended, using <code>echo</code> is considered common practice.</p> </li> <li> <p>Never use options to <code>echo</code>! Ever! Any time you feel tempted to use <code>echo -e</code>, <code>-n</code>, or any other special feature of echo, use printf instead! If portability is a requirement, you should consider using <code>printf</code> exclusively and just ignore that <code>echo</code> even exists. If you must use <code>echo -e</code> and refuse to use <code>printf</code>, it is usually acceptable to use \\'\\'echo \\$\\'...\\' \\'\\'if targeting only shells that support this special quoting style.</p> </li> <li> <p><code>ksh93</code> has a <code>print</code> command, which if coding specifically for <code>ksh93</code> should be preferred over <code>echo</code>. printf still includes most of the functionality of both, and should usually be the most preferred option.</p> </li> </ul>"},{"location":"commands/builtin/echo/#see-also","title":"See also","text":"<ul> <li>printf</li> <li>http://cfajohnson.com/shell/cus-faq.html#Q0b</li> <li>http://www.in-ulm.de/~mascheck/various/echo+printf/</li> </ul>"},{"location":"commands/builtin/eval/","title":"The eval builtin command","text":""},{"location":"commands/builtin/eval/#synopsis","title":"Synopsis","text":"<pre><code>eval: eval [arg ...]\n</code></pre>"},{"location":"commands/builtin/eval/#description","title":"Description","text":"<p><code>eval</code> takes its arguments, concatenates them separated by spaces, and executes the resulting string as Bash code in the current execution environment. <code>eval</code> in Bash works in essentially the same way as most other languages that have an <code>eval</code> function. Perhaps the easiest way to think about <code>eval</code> is that it works in the same way as running \\'\\'bash -c \\\"bash code...\\\" \\'\\'from a script, except in the case of <code>eval</code>, the given code is executed in the current shell environment rather than a child process.</p>"},{"location":"commands/builtin/eval/#examples","title":"Examples","text":"<p>In this example, the literal text within the here-document is executed as Bash code exactly as though it were to appear within the script in place of the <code>eval</code> command below it.</p> <pre><code>#!/usr/bin/env bash\n{ myCode=$(&lt;/dev/stdin); } &lt;&lt;\\EOF\n... arbitrary bash code here ...\nEOF\n\neval \"$myCode\"\n</code></pre>"},{"location":"commands/builtin/eval/#expansion-side-effects","title":"Expansion side-effects","text":"<p>Frequently, <code>eval</code> is used to cause side-effects by performing a pass of expansion on the code before executing the resulting string. This allows for things that otherwise wouldn't be possible with ordinary Bash syntax. This also, of course, makes <code>eval</code> the most powerful command in all of shell programming (and in most other languages for that matter).</p> <p>This code defines a set of identical functions using the supplied names. <code>eval</code> is the only way to achieve this effect.</p> <pre><code>main() {\n local fun='() { echo \"$FUNCNAME\"; }' x\n\n for x in {f..n}; do\n eval \"${x}${fun}\"\n done\n\n \"$@\"\n}\n\nmain \"$@\"\n</code></pre>"},{"location":"commands/builtin/eval/#using-printf-q","title":"Using printf %q","text":"<p>The <code>printf %q</code> format string performs shell escaping on its arguments. This makes <code>printf %q</code> the \"anti-eval\" - with each pass of a string through printf requiring another <code>eval</code> to peel off the escaping again.</p> <pre><code>while (( ++n &lt;= 5 )) || ! evalBall=\"eval $evalBall\"; do\n printf -v evalBall 'eval %q' \"printf $n;${evalBall-printf '0\\n'}\"\ndone\n$evalBall\n</code></pre> <p>The above example is mostly fun and games but illustrates the <code>printf %q</code> property.</p>"},{"location":"commands/builtin/eval/#higher-order-functions","title":"Higher-order functions","text":"<p>Since all current POSIX-compatible shells lack support for first-class functions, it can be tempting and sometimes useful to simulate some of their effect using <code>eval</code> to evaluate a string containing code.</p> <p>This example shows partial application using <code>eval</code>.</p> <pre><code>function partial {\n eval shift 2 \\; function \"$1\" \\{ \"$2\" \"$(printf '%q ' \"${@:3}\")\" '\"$@\"; }'\n}\n\nfunction repeat {\n [[ $1 == +([0-9]) ]] || return\n typeset n\n while ((n++ &lt; $1)); do\n \"${@:2}\"\n done\n}\n\npartial print3 repeat 3 printf '%s ' # Create a new function named print3\nprint3 hi # Print \"hi\" 3 times\necho\n</code></pre> <p>This is very easy to do incorrectly and not usually considered idiomatic of Bash if used extensively. However abstracting eval behind functions that validate their input and/or make clear which input must be controlled carefully by the caller is a good way to use it.</p>"},{"location":"commands/builtin/eval/#portability-considerations","title":"Portability considerations","text":"<ul> <li> <p>Unfortunately, because eval is a special builtin, it only gets its own environment in Bash, and only when Bash is not in POSIX mode. In all other shells plus Bash in POSIX mode, the environment of eval will leak out into the surrounding environment. It is possible to work around this limitation by prefixing special builtins with the <code>command</code> regular builtin, but current versions of ~~ksh93~~ and zsh don't do this properly (fixed in ksh 93v- 2012-10-24 alpha). Earlier versions of zsh work (with <code>setopt POSIX_BUILTINS</code> -- looks like a regression). This works correctly in Bash POSIX mode, Dash, and mksh.</p> </li> <li> <p><code>eval</code> is another one of the few Bash builtins with keyword-like conditional parsing of arguments that are in the form of compound assignments.</p> <p>$ ( eval a=( a b\\ c d ); printf '&lt;%s&gt; ' \"${a[@]}\"; echo ) # Only works in Bash. $ ( x=a; eval \"$x\"=( a b\\ c d ); printf '&lt;%s&gt; ' \"${a[@]}\"; echo ) # Argument is no longer in the form of a valid assignment, therefore ordinary parsing rules apply. -bash: syntax error near unexpected token `(' $ ( x=a; eval \"$x\"'=( a b\\ c d )'; printf '&lt;%s&gt; ' \"${a[@]}\"; echo ) # Proper quoting then gives us the expected results. <p>We don't know why Bash does this. Since parentheses are metacharacters, they must ordinary be quoted or escaped when used as arguments. The first example above is the same error as the second in all non-Bash shells, even those with compound assignment.</p> <p>In the case of <code>eval</code> it isn't recommended to use this behavior, because unlike e.g. declare, the initial expansion is still subject to all expansions including word-splitting and pathname expansion.</p> <pre><code> $ ( set -x; touch 'x+=(\\[[123]\\]=*)' 'x+=([3]=yo)'; eval x+=(*); echo \"${x[@]}\" )\n+ touch 'x+=(\\[[123]\\]=*)' 'x+=([3]=yo)'\n+ eval 'x+=(\\[[123]\\]=*)' 'x+=([3]=yo)'\n++ x+=(\\[[123]\\]=*)\n++ x+=([3]=yo)\n+ echo '[[123]]=*' yo\n[[123]]=* yo\n</code></pre> <p>Other commands known to be affected by compound assignment arguments include: let, declare, <code>typeset</code>, local, export, and readonly. More oddities below show both similarities and differences to commands like declare. The rules for <code>eval</code> appear identical to those of let.</p>"},{"location":"commands/builtin/eval/#see-also","title":"See also","text":"<ul> <li>BashFAQ 48 - eval and security issues -- IMPORTANT</li> <li>Another eval article</li> <li>Indirection via eval</li> <li>More indirection via eval</li> <li>Martin V\u00e4th's \"push\" -- <code>printf %q</code> work-alike for POSIX.</li> <li>The \"magic alias\" hack</li> </ul>"},{"location":"commands/builtin/exec/","title":"The exec builtin command","text":""},{"location":"commands/builtin/exec/#synopsis","title":"Synopsis","text":"<pre><code>exec [-a NAME] [-cl] [COMMAND] [ARG...] [REDIRECTION...]\n</code></pre>"},{"location":"commands/builtin/exec/#description","title":"Description","text":"<p>The <code>exec</code> builtin command is used to</p> <ul> <li>replace the shell with a given program (executing it, not as new process)</li> <li>set redirections for the program to execute or for the current shell</li> </ul> <p>If only redirections are given, the redirections affect the current shell without executing any program.</p>"},{"location":"commands/builtin/exec/#options","title":"Options","text":"Option Description <code>-a NAME</code> Passes <code>NAME</code> as zeroth argument for the program to be executed <code>-c</code> Execute the program with an empty (cleared) environment <code>-l</code> Prepends a dash (<code>-</code>) to the zeroth argument of the program to be executed, similar to what the <code>login</code> program does"},{"location":"commands/builtin/exec/#exit-status","title":"Exit status","text":"<ul> <li>on redirection errors it returns 1, otherwise 0</li> <li>on exec failures:<ul> <li>a non-interactive shell terminates; if the shell option execfail is set <code>exec</code> returns failure</li> <li>in an interactive shell, <code>exec</code> returns failure</li> </ul> </li> </ul>"},{"location":"commands/builtin/exec/#examples","title":"Examples","text":""},{"location":"commands/builtin/exec/#wrapper-around-a-program","title":"Wrapper around a program","text":"<pre><code>myprog=/bin/ls\necho \"This is the wrapper script, it will exec $myprog\"\n\n# do some vodoo here, probably change the arguments etc.\n# well, stuff a wrapper is there for\n\nexec \"$myprog\" \"$@\"\n</code></pre>"},{"location":"commands/builtin/exec/#open-a-file-as-input-for-the-script","title":"Open a file as input for the script","text":"<pre><code># open it\nexec 3&lt; input.txt\n\n# for example: read one line from the file(-descriptor)\nread -u 3 LINE\n# or\nread LINE &lt;&amp;3\n\n# finally, close it\nexec 3&lt;&amp;-\n</code></pre>"},{"location":"commands/builtin/exec/#overall-script-logfile","title":"Overall script logfile","text":"<p>To redirect the whole <code>stdout</code> and <code>stderr</code> of the shell or shellscript to a file, you can use the <code>exec</code> builtin command:</p> <pre><code>exec &gt;/var/adm/my.log 2&gt;&amp;1\n\n# script continues here...\n</code></pre>"},{"location":"commands/builtin/exec/#portability-considerations","title":"Portability considerations","text":"<pre><code>*POSIX(r) specifies error code ranges:\n * if ''exec'' can't find the program to execute, the error code shall be 126\n * on a redirection error, the error code shall be between 1 and 125\n* the ''-a NAME'' option appeared in Bash 4.2-alpha\n* POSIX(r) does **not** specify any options for ''exec'' (like ''-c'', ''-l'', ''-a NAME'').\n</code></pre>"},{"location":"commands/builtin/exec/#see-also","title":"See also","text":"<ul> <li>redirection</li> </ul>"},{"location":"commands/builtin/exit/","title":"The exit builtin command","text":""},{"location":"commands/builtin/exit/#synopsis","title":"Synopsis","text":"<pre><code>exit [N]\n</code></pre>"},{"location":"commands/builtin/exit/#description","title":"Description","text":"<p>The <code>exit</code> command terminates the current shell (or script).</p> <p>If <code>N</code> is given, the return code to the parent process is set to <code>N</code>. If not, the returned status the the status of the most recently executed command (i.e. <code>$?</code>).</p> <p>A trap on <code>EXIT</code> is executed before the shell exits, except the executed <code>exit</code> command is part of an already running trap.</p>"},{"location":"commands/builtin/exit/#options","title":"Options","text":"<p>There are no options.</p>"},{"location":"commands/builtin/exit/#exit-status","title":"Exit status","text":"<p>Naturally, you can't ask for the exit status from within the shell that executed the <code>exit</code> command, because the shell exits.</p> Status Reason 255 invalid (e.g. non-numeric) argument - this staus is returned to the parent"},{"location":"commands/builtin/exit/#examples","title":"Examples","text":""},{"location":"commands/builtin/exit/#exit-the-shell-and-explicitely-set-its-exit-status","title":"Exit the shell and explicitely set its exit status","text":"<pre><code>exit 3\n</code></pre>"},{"location":"commands/builtin/exit/#portability-considerations","title":"Portability considerations","text":"<ul> <li>if <code>N</code> is specified, but its value is not between 0 and 255 inclusively, the exit status is undefined.</li> </ul>"},{"location":"commands/builtin/exit/#see-also","title":"See also","text":"<ul> <li>The trap builtin command</li> <li>The exit status</li> </ul>"},{"location":"commands/builtin/export/","title":"The export builtin command","text":""},{"location":"commands/builtin/export/#synopsis","title":"Synopsis","text":"<pre><code>export [-fn] [NAME[=VALUE] ...]\nexport -p\n</code></pre>"},{"location":"commands/builtin/export/#description","title":"Description","text":"<p>The <code>export</code> builtin command is used to mark variables or functions referenced by <code>NAME</code> for automatic export to the environment. If <code>NAME</code> is a shell variable, a value <code>VALUE</code> can be assigned before exporting it.</p>"},{"location":"commands/builtin/export/#options","title":"Options","text":"Option Description <code>-f</code> refer to shell functions <code>-n</code> remove the export property from any referenced <code>NAME</code> <code>-p</code> print all exported variables, with <code>-f</code>, print all exported functions - all in a format re-usable as input <p>An argument of <code>--</code> disables further option processing.</p>"},{"location":"commands/builtin/export/#return-status","title":"Return status","text":"Status Reason 0 no error !=0 invalid option !=0 a given <code>NAME</code> is invalid"},{"location":"commands/builtin/export/#examples","title":"Examples","text":"<p>Set the display to use when launching a GUI application (useful during SSH sessions):</p> <pre><code>export DISPLAY=\":0\"\n</code></pre> <p>Set your default text editor (e.g. SublimeText):</p> <pre><code>export EDITOR=subl\n</code></pre>"},{"location":"commands/builtin/export/#portability-considerations","title":"Portability considerations","text":"<ul> <li>in POSIX\u00ae, only the <code>-p</code> option is specified</li> <li>in POSIX\u00ae, only variables (with value assignment) are to be exported, not shell functions</li> </ul>"},{"location":"commands/builtin/export/#see-also","title":"See also","text":"<ul> <li>declare</li> </ul>"},{"location":"commands/builtin/kill/","title":"The kill builtin command","text":""},{"location":"commands/builtin/kill/#synopsis","title":"Synopsis","text":"<pre><code>kill [-s SIGNAL | -n SIGNALNUMBER | -SIGNAL] PID|JOB\n\nkill -l|-L [SIGNAL...]\n</code></pre>"},{"location":"commands/builtin/kill/#description","title":"Description","text":"<p>The <code>kill</code> command is used to send signals to processes specified by their <code>PID</code> or their <code>JOB</code>-specification.</p> <p>The signal(s) to be specified can have the following formats:</p> <ul> <li>Numerical: The signal is specified using its constant numeric value. Be aware that not all systems have identical numbers for the signals.</li> <li>Symbolic (long): The signal is specified using the same name that is used for the constant/macro in the C API (<code>SIG&lt;name&gt;</code>)</li> <li>Symbolic (short): The signal is specified using the name from the C API without the <code>SIG</code>-prefix (<code>&lt;name&gt;</code>)</li> </ul> <p>Without any specified signal, the command sends the <code>SIGTERM</code>-signal.</p> <p>The <code>kill</code> command is a Bash builtin command instead of relying on the external <code>kill</code> command of the operating system to</p> <ul> <li>be able to use shell job specifications instead of Unix process IDs</li> <li>be able to send signals (\"kill something\") also, when your process limit is reached</li> </ul>"},{"location":"commands/builtin/kill/#options","title":"Options","text":"Option Description <code>-s SIGNAL</code> specifies the signal to send <code>-n SIGNALNUMBER</code> specifies the signal to send <code>-SIGNAL</code> specifies the signal to send <code>-l [SIGNAL...]</code> Lists supported/known signal numbers and their symbolic name. If <code>SIGNAL</code> is given, only list this signal, translated (if a number is given the symbolic name is printed, and vice versa) <code>-L [SIGNAL...]</code> Same as <code>-l [SIGNAL]</code> (compatiblity option)"},{"location":"commands/builtin/kill/#return-status","title":"Return status","text":"Status Reason 0 no error/success !=0 invalid option !=0 invalid signal specification !=0 error returned by the system function (e.g. insufficient permissions to send to a specific process)"},{"location":"commands/builtin/kill/#examples","title":"Examples","text":""},{"location":"commands/builtin/kill/#list-supported-signals","title":"List supported signals","text":"<pre><code>kill -l\n</code></pre>"},{"location":"commands/builtin/kill/#send-kill-to-a-process-id","title":"Send KILL to a process ID","text":"<pre><code>kill -9 12345\n\nkill -KILL 12345\n\nkill -SIGKILL 12345\n</code></pre>"},{"location":"commands/builtin/kill/#portability-considerations","title":"Portability considerations","text":"<ul> <li>POSIX(R) and ISO C only standardize symbolic signal names (no numbers) and a default action</li> </ul>"},{"location":"commands/builtin/kill/#see-also","title":"See also","text":""},{"location":"commands/builtin/let/","title":"The let builtin command","text":""},{"location":"commands/builtin/let/#synopsis","title":"Synopsis","text":"<pre><code>let arg [arg ...]\n</code></pre>"},{"location":"commands/builtin/let/#description","title":"Description","text":"<p>The <code>let</code> builtin command evaluates each supplied word from left to right as an arithmetic expression and returns an exit code according to the truth value of the rightmost expression.</p> <ul> <li>0 (TRUE) when <code>arg</code> evaluated to not 0 (arithmetic \"true\")</li> <li>1 (FALSE) when <code>arg</code> evaluated to 0 (arithmetic \"false\")</li> </ul> <p>For this return code mapping, please see this section. They work in the same way as <code>((</code>.</p>"},{"location":"commands/builtin/let/#examples","title":"Examples","text":"<p><code>let</code> is very similar to (( - the only difference being <code>let</code> is a builtin (simple command), and <code>((</code> is a compound command. The arguments to <code>let</code> are therefore subject to all the same expansions and substitutions as any other simple command - requiring proper quoting and escaping - whereas the contents of <code>((</code> aren't subject to word-splitting or pathname expansion (almost never desirable for arithmetic). For this reason, the arithmetic compound command should generally be preferred over <code>let</code>.</p> <pre><code>$ let 'b = a' \"(a += 3) + $((a = 1)), b++\"\n$ echo \"$a - $b - $?\"\n4 - 2 - 0\n</code></pre> <p>Is equivalent to the arithmetic evaluation compound command:</p> <pre><code>$ (( b = a, (a += 3) + $((a = 1)), b++ ))\n$ echo \"$a - $b - $?\"\n4 - 2 - 0\n</code></pre> <p>Remember that inside arithmetic evaluation contexts, all other expansions are processed as usual (from left-to-right), and the resulting text is evaluated as an arithmetic expression. Arithmetic already has a way to control precedence using parentheses, so it's very rare to need to nest arithmetic expansions within one another. It's used above only to illustrate how this precedence works.</p> <p>Unlike <code>((</code>, being a simple command <code>let</code> has its own environment. In Bash, built-ins that can set variables process any arithmetic under their own environment, which makes the variable effectively \"local\" to the builtin unless the variable is also set or modified by the builtin. This differs in other shells, such as ksh93, where environment assignments to regular builtins are always local even if the variable is modified by the builtin.</p> <pre><code> ~ $ ( y=1+1 let x=y; declare -p x y )\ndeclare -- x=\"2\"\nbash: declare: y: not found\n\n ~ $ ( y=1+1 let x=y++; declare -p x y )\ndeclare -- x=\"2\"\ndeclare -- y=\"3\"\n</code></pre> <p>This can be useful in certain situations where a temporary variable is needed.</p>"},{"location":"commands/builtin/let/#portability-considerations","title":"Portability considerations","text":"<ul> <li>the <code>let</code> command is not specified by POSIX\u00ae. The portable alternative is: <code>[ \"$(( &lt;EXPRESSION&gt; ))\" -ne 0 ]</code>. To make portable scripts simpler and cleaner, <code>let</code> can be defined as: <code># POSIX let() { IFS=, command eval test '$(($*))' -ne 0 }</code> Aside from differences in supported arithmetic features, this should be identical to the Bash/Ksh <code>let</code>.</li> <li>It seems to be a common misunderstanding that <code>let</code> has some legacy purpose. Both <code>let</code> and <sup>1</sup> were ksh88 features and almost identical in terms of portability as everything that inherited one also tended to get the other. Don't choose <code>let</code> over <code>((</code> expecting it to work in more places.</li> <li>expr(1) is a command one is likely to come across sooner or later. While it is more \"standard\" than <code>let</code>, the above should always be preferred. Both arithmetic expansions and the <code>[</code> test operator are specified by POSIX\u00ae and satisfy almost all of expr's use-cases. Unlike <code>let</code>, <code>expr</code> cannot assign directly to bash variables but instead returns a result on stdout. <code>expr</code> takes each operator it recognizes as a separate word and then concatenates them into a single expression that's evaluated according to it's own rules (which differ from shell arithmetic). <code>let</code> parses each word it recieves on its own and evaluates it as an expression without generating any output other than a return code.</li> <li>For unknown reasons, <code>let</code> is one of the Bash commands with special parsing for arguments formatted like compound array assignments. See: eval for details. There are no known practical uses for this. Parentheses are treated as grouping operators and compound assignment is not possible by arithmetic expressions.</li> </ul>"},{"location":"commands/builtin/let/#see-also","title":"See also","text":"<ul> <li>Internal: arithmetic expansion</li> <li>Internal: arithmetic expressions</li> <li>Internal: arithmetic evaluation compound command</li> </ul> <ol> <li> <p>...\u00a0\u21a9</p> </li> </ol>"},{"location":"commands/builtin/local/","title":"The local builtin command","text":""},{"location":"commands/builtin/local/#synopsis","title":"Synopsis","text":"<pre><code>local [option] name[=value] ...\n</code></pre>"},{"location":"commands/builtin/local/#description","title":"Description","text":"<p><code>local</code> is identical to declare in every way, and takes all the same options, with 3 exceptions:</p> <ul> <li>Usage outside of a function is an error. Both <code>declare</code> and <code>local</code> within a function have the same effect on variable scope, including the -g option.</li> <li><code>local</code> with no options prints variable names and values in the same format as <code>declare</code> with no options, except the variables are filtered to print only locals that were set in the same scope from which <code>local</code> was called. Variables in parent scopes are not printed.</li> <li>If name is '-', the set of shell options is made local to the function in which local is invoked: shell options changed using the set builtin inside the function are restored to their original values when the function returns. The restore is effected as if a series of set commands were executed to restore the values that were in place before the function.</li> </ul>"},{"location":"commands/builtin/local/#portability-considerations","title":"Portability considerations","text":"<ul> <li> <p><code>local</code> is not specified by POSIX. Most bourne-like shells don't have a builtin called <code>local</code>, but some such as <code>dash</code> and the busybox shell do.</p> </li> <li> <p>The behavior of function scope is not defined by POSIX, however local variables are implemented widely by bourne-like shells, and behavior differs substantially. Even the<code>dash</code> shell has local variables.</p> </li> <li> <p>In ksh93, using POSIX-style function definitions, <code>typeset</code> doesn't set <code>local</code> variables, but rather acts upon variables of the next-outermost scope (e.g. setting attributes). Using <code>typeset</code> within functions defined using ksh <code>function name {</code> syntax, variables follow roughly lexical-scoping, except that functions themselves don't have scope, just like Bash. This means that even functions defined within a \"function's scope\" don't have access to non-local variables except through <code>namerefs</code>.</p> </li> </ul>"},{"location":"commands/builtin/local/#see-also","title":"See also","text":"<ul> <li>The basics of shell scripting: Variable scope</li> </ul>"},{"location":"commands/builtin/mapfile/","title":"The mapfile builtin command","text":""},{"location":"commands/builtin/mapfile/#synopsis","title":"Synopsis","text":"<pre><code>mapfile [-n COUNT] [-O ORIGIN] [-s COUNT] [-t] [-u FD] [-C CALLBACK] [-c QUANTUM] [ARRAY]\n\nreadarray [-n COUNT] [-O ORIGIN] [-s COUNT] [-t] [-u FD] [-C CALLBACK] [-c QUANTUM] [ARRAY]\n</code></pre>"},{"location":"commands/builtin/mapfile/#description","title":"Description","text":"<p>This builtin is also accessible using the command name <code>readarray</code>.</p> <p><code>mapfile</code> is one of the two builtin commands primarily intended for handling standard input (the other being <code>read</code>). <code>mapfile</code> reads lines of standard input and assigns each to the elements of an indexed array. If no array name is given, the default array name is <code>MAPFILE</code>. The target array must be a \"normal\" integer indexed array.</p> <p><code>mapfile</code> returns success (0) unless an invalid option is given or the given array <code>ARRAY</code> is set readonly.</p> Option Description <code>-c QUANTUM</code> Specifies the number of lines that have to be read between every call to the callback specified with <code>-C</code>. The default QUANTUM is 5000 <code>-C CALLBACK</code> Specifies a callback. The string <code>CALLBACK</code> can be any shell code, the index of the array that will be assigned, and the line is appended at evaluation time. <code>-n COUNT</code> Reads at most <code>COUNT</code> lines, then terminates. If <code>COUNT</code> is 0, then all lines are read (default). <code>-O ORIGIN</code> Starts populating the given array <code>ARRAY</code> at the index <code>ORIGIN</code> rather than clearing it and starting at index 0. <code>-s COUNT</code> Discards the first <code>COUNT</code> lines read. <code>-t</code> Remove any trailing newline from a line read, before it is assigned to an array element. <code>-u FD</code> Read from filedescriptor <code>FD</code> rather than standard input. <p>While <code>mapfile</code> isn't a common or portable shell feature, it's functionality will be familiar to many programmers. Almost all programming languages (aside from shells) with support for compound datatypes like arrays, and which handle open file objects in the traditional way, have some analogous shortcut for easily reading all lines of some input as a standard feature. In Bash, <code>mapfile</code> in itself can't do anything that couldn't already be done using read and a loop, and if portability is even a slight concern, should never be used. However, it does significantly outperform a read loop, and can make for shorter and cleaner code - especially convenient for interactive use.</p>"},{"location":"commands/builtin/mapfile/#examples","title":"Examples","text":"<p>Here's a real-world example of interactive use borrowed from Gentoo workflow. Xorg updates require rebuilding drivers, and the Gentoo-suggested command is less than ideal, so let's Bashify it. The first command produces a list of packages, one per line. We can read those into the array named \"args\" using <code>mapfile</code>, stripping trailing newlines with the '<code>-t</code>' option. The resulting array is then expanded into the arguments of the <code>emerge</code> command - an interface to Gentoo's package manager. This type of usage can make for a safe and effective replacement for xargs(1) in certain situations. Unlike xargs, all arguments are guaranteed to be passed to a single invocation of the command with no wordsplitting, pathname expansion, or other monkey business.</p> <pre><code># eix --only-names -IC x11-drivers | { mapfile -t args; emerge -av1 \"${args[@]}\" &lt;&amp;1; }\n</code></pre> <p>Note the use of command grouping to keep the emerge command inside the pipe's subshell and within the scope of \"args\". Also note the unusual redirection. This is because the -a flag makes emerge interactive, asking the user for confirmation before continuing, and checking with isatty(3) to abort if stdin isn't pointed at a terminal. Since stdin of the entire command group is still coming from the pipe even though mapfile has read all available input, we just borrow FD 1 as it just so happens to be pointing where we want it. More on this over at greycat's wiki: http://mywiki.wooledge.org/BashFAQ/024</p>"},{"location":"commands/builtin/mapfile/#the-callback","title":"The callback","text":"<p>This is one of the more unusual features of a Bash builtin. As far as I'm able to tell, the exact behavior is as follows: If defined, as each line is read, the code contained within the string argument to the -C flag is evaluated and executed before the assignment of each array element. There are no restrictions to this string, which can be any arbitrary code, however, two additional \"words\" are automatically appended to the end before evaluation: the index, and corresponding line of data to be assigned to the next array element. Since all this happens before assignment, the callback feature cannot be used to modify the element to be assigned, though it can read and modify any array elements already assigned.</p> <p>A very simple example might be to use it as a kind of progress bar. This will print a dot for each line read. Note the escaped comment to hide the appended words from printf.</p> <pre><code>$ printf '%s\\n' {1..5} | mapfile -c 1 -C 'printf . \\#' )\n.....\n</code></pre> <p>Really, the intended usage is for the callback to just contain the name of a function, with the extra words passed to it as arguments. If you're going to use callbacks at all, this is probably the best way because it allows for easy access to the arguments with no ugly \"code in a string\".</p> <pre><code>$ foo() { echo \"|$1|\"; }; mapfile -n 11 -c 2 -C 'foo' &lt;file\n|2|\n|4|\netc..\n</code></pre> <p>For the sake of completeness, here are some more complicated examples inspired by a question asked in #bash - how to prepend something to every line of some input, and then output even and odd lines to separate files. This is far from the best possible answer, but hopefully illustrates the callback behavior:</p> <pre><code>$ { printf 'input%s\\n' {1..10} | mapfile -c 1 -C '&gt;&amp;$(( (${#x[@]} % 2) + 3 )) printf -- \"%.sprefix %s\"' x; } 3&gt;outfile0 4&gt;outfile1\n$ cat outfile{0,1}\nprefix input1\nprefix input3\nprefix input5\nprefix input7\nprefix input9\nprefix input2\nprefix input4\nprefix input6\nprefix input8\nprefix input10\n</code></pre> <p>Since redirects are syntactically allowed anywhere in a command, we put it before the printf to stay out of the way of additional arguments. Rather than opening \"outfile&lt;n&gt;\" for appending on each call by calculating the filename, open an FD for each first and calculate which FD to send output to by measuring the size of x mod 2. The zero-width format specification is used to absorb the index number argument.</p> <p>Another variation might be to add each of these lines to the elements of separate arrays. I'll leave dissecting this one as an exercise for the reader. This is quite the hack but illustrates some interesting properties of printf -v and mapfile -C (which you should probably never use in real code).</p> <pre><code>$ y=( 'odd[j]' 'even[j++]' ); printf 'input%s\\n' {1..10} | { mapfile -tc 1 -C 'printf -v \"${y[${#x[@]} % 2]}\" -- \"%.sprefix %s\"' x; printf '%s\\n' \"${odd[@]}\" '' \"${even[@]}\"; }\nprefix input1\nprefix input3\nprefix input5\nprefix input7\nprefix input9\n\nprefix input2\nprefix input4\nprefix input6\nprefix input8\nprefix input10\n</code></pre> <p>This example based on yet another #bash question illustrates mapfile in combination with read. The sample input is the heredoc to <code>main</code>. The goal is to build a \"struct\" based upon records in the input file made up of the numbers following the colon on each line. Every 3<sup>rd</sup> line is a key followed by 2 corresponding fields. The showRecord function takes a key and returns the record.</p> <pre><code>#!/usr/bin/env bash\n\nshowRecord() {\n printf 'key[%d] = %d, %d\\n' \"$1\" \"${vals[@]:keys[$1]*2:2}\"\n}\n\nparseRecords() {\n trap 'unset -f _f' RETURN\n _f() {\n local x\n IFS=: read -r _ x\n ((keys[x]=n++))\n }\n local n\n\n _f\n mapfile -tc2 -C _f \"$1\"\n eval \"$1\"'=(\"${'\"$1\"'[@]##*:}\")' # Return the array with some modification\n}\n\nmain() {\n local -a keys vals\n parseRecords vals\n showRecord \"$1\"\n}\n\nmain \"$1\" &lt;&lt;-\"EOF\"\nfabric.domain:123\nroutex:1\nroutey:2\nfabric.domain:321\nroutex:6\nroutey:4\nEOF\n</code></pre> <p>For example, running <code>scriptname 321</code> would output <code>key[321] = 6, 4</code>. Every 2 lines read by <code>mapfile</code>, the function <code>_f</code> is called, which reads one additional line. Since the first line in the file is a key, and <code>_f</code> is responsible for the keys, it gets called first so that <code>mapfile</code> starts by reading the second line of input, calling <code>_f</code> with each subsequent 2 iterations. The RETURN trap is unimportant.</p>"},{"location":"commands/builtin/mapfile/#bugs","title":"Bugs","text":"<ul> <li>Early implementations were buggy. For example, <code>mapfile</code> filling the readline history buffer with calls to the <code>CALLBACK</code>. This was fixed in 4.1 beta.</li> <li><code>mapfile -n</code> reads an extra line beyond the last line assigned to the array, through Bash. Fixed in 4.2.35.</li> <li><code>mapfile</code> callbacks could cause a crash if the variable being assigned is manipulated in certain ways. https://lists.gnu.org/archive/html/bug-bash/2013-01/msg00039.html. Fixed in 4.3.</li> </ul>"},{"location":"commands/builtin/mapfile/#to-do","title":"To Do","text":"<ul> <li>Create an implementation as a shell function that's portable between Ksh, Zsh, and Bash (and possibly other bourne-like shells with array support).</li> </ul>"},{"location":"commands/builtin/mapfile/#see-also","title":"See also","text":"<ul> <li>arrays</li> <li>read - If you don't know about this yet, why are you reading this page?</li> <li>http://mywiki.wooledge.org/BashFAQ/001 - It's FAQ 1 for a reason.</li> </ul>"},{"location":"commands/builtin/printf/","title":"The printf command","text":"<p>FIXME</p> <p>This is a very big topic that needs experience - please fill in missing information, extend the descriptions, and correct the details if you can!</p> <p>Bash-Builtin</p> <p>This is about the Bash-builtin command <code>printf</code> - however, the description should be nearly identical for an external command that follows POSIX\u00ae.</p> <p>GNU Awk expects a comma after the format string and between each of the arguments of a printf command. For examples, see: code snippet.</p> <p>Unlike other documentations, I don't want to redirect you to the manual page for the <code>printf()</code> C function family. However, if you're more experienced, that should be the most detailed description for the format strings and modifiers.</p> <p>Due to conflicting historical implementations of the <code>echo</code> command, POSIX\u00ae recommends that <code>printf</code> is preferred over <code>echo</code>.</p>"},{"location":"commands/builtin/printf/#general","title":"General","text":"<p>The <code>printf</code> command provides a method to print preformatted text similar to the <code>printf()</code> system interface (C function). It's meant as successor for <code>echo</code> and has far more features and possibilities.</p> <p>Beside other reasons, POSIX\u00ae has a very good argument to recommend it: Both historical main flavours of the <code>echo</code> command are mutual exclusive, they collide. A \"new\" command had to be invented to solve the issue.</p>"},{"location":"commands/builtin/printf/#syntax","title":"Syntax","text":"<pre><code>printf &lt;FORMAT&gt; &lt;ARGUMENTS...&gt;\n</code></pre> <p>The text format is given in <code>&lt;FORMAT&gt;</code>, while all arguments the formatstring may point to are given after that, here, indicated by <code>&lt;ARGUMENTS...&gt;</code>.</p> <p>Thus, a typical <code>printf</code>-call looks like:</p> <pre><code>printf \"Surname: %s\\nName: %s\\n\" \"$SURNAME\" \"$FIRSTNAME\"\n</code></pre> <p>where <code>\"Surname: %s\\nName: %s\\n\"</code> is the format specification, and the two variables are passed as arguments, the <code>%s</code> in the formatstring points to (for every format specifier you give, <code>printf</code> awaits one argument!).</p>"},{"location":"commands/builtin/printf/#options","title":"Options","text":"Option Description <code>-v VAR</code> If given, the output is assigned to the variable <code>VAR</code> instead of printed to <code>stdout</code> (comparable to <code>sprintf()</code> in some way) <p>The <code>-v</code> Option can't assign directly to array indexes in Bash versions older than Bash 4.1.</p> <p>Danger</p> <p>In versions newer than 4.1, one must be careful when performing expansions into the first non-option argument of printf as this opens up the possibility of an easy code injection vulnerability.</p> <pre><code>$ var='-vx[$(echo hi &gt;&amp;2)]'; printf \"$var\" hi; declare -p x\nhi\ndeclare -a x='([0]=\"hi\")'\n</code></pre> <p>...where the echo can of course be replaced with any arbitrary command. If you must, either specify a hard-coded format string or use -- to signal the end of options. The exact same issue also applies to read, and a similar one to mapfile, though performing expansions into their arguments is less common.</p>"},{"location":"commands/builtin/printf/#arguments","title":"Arguments","text":"<p>Of course in shell-meaning the arguments are just strings, however, the common C-notations plus some additions for number-constants are recognized to give a number-argument to <code>printf</code>:</p> Number-Format Description <code>N</code> A normal decimal number <code>0N</code> An octal number <code>0xN</code> A hexadecimal number <code>0XN</code> A hexadecimal number <code>\"X</code> (a literal double-quote infront of a character): interpreted as number (underlying codeset) don't forget escaping <code>'X</code> (a literal single-quote infront of a character): interpreted as number (underlying codeset) don't forget escaping <p>If more arguments than format specifiers are present, then the format string is re-used until the last argument is interpreted. If fewer format specifiers than arguments are present, then number-formats are set to zero, while string-formats are set to null (empty).</p> <p>Take care to avoid word splitting, as accidentally passing the wrong number of arguments can produce wildly different and unexpected results. See this article.</p> <p>Attention</p> <p>When a numerical format expects a number, the internal <code>printf</code>-command will use the common Bash arithmetic rules regarding the base. A command like the following example will throw an error, since <code>08</code> is not a valid octal number (<code>00</code> to <code>07</code>!):</p> <pre><code>printf '%d\\n' 08\n</code></pre>"},{"location":"commands/builtin/printf/#format-strings","title":"Format strings","text":"<p>The format string interpretion is derived from the C <code>printf()</code> function family. Only format specifiers that end in one of the letters <code>diouxXfeEgGaAcs</code> are recognized.</p> <p>To print a literal <code>%</code> (percent-sign), use <code>%%</code> in the format string.</p> <p>Again: Every format specifier expects an associated argument provided!</p> <p>These specifiers have different names, depending who you ask. But they all mean the same: A placeholder for data with a specified format:</p> <ul> <li>format placeholder</li> <li>conversion specification</li> <li>formatting token</li> <li>...</li> </ul> Format Description <code>%b</code> Print the associated argument while interpreting backslash escapes in there <code>%q</code> Print the associated argument shell-quoted, reusable as input <code>%d</code> Print the associated argument as signed decimal number <code>%i</code> Same as <code>%d</code> <code>%o</code> Print the associated argument as unsigned octal number <code>%u</code> Print the associated argument as unsigned decimal number <code>%x</code> Print the associated argument as unsigned hexadecimal number with lower-case hex-digits (a-f) <code>%X</code> Same as <code>%x</code>, but with upper-case hex-digits (A-F) <code>%f</code> Interpret and print the associated argument as floating point number <code>%e</code> Interpret the associated argument as double, and print it in <code>&lt;N&gt;\u00b1e&lt;N&gt;</code> format <code>%E</code> Same as <code>%e</code>, but with an upper-case <code>E</code> in the printed format <code>%g</code> Interprets the associated argument as double, but prints it like <code>%f</code> or <code>%e</code> <code>%G</code> Same as <code>%g</code>, but print it like <code>%E</code> <code>%c</code> Interprets the associated argument as char: only the first character of a given argument is printed <code>%s</code> Interprets the associated argument literally as string <code>%n</code> Assigns the number of characters printed so far to the variable named in the corresponding argument. Can't specify an array index. If the given name is already an array, the value is assigned to the zeroth element. <code>%a</code> Interprets the associated argument as double, and prints it in the form of a C99 hexadecimal floating-point literal. <code>%A</code> Same as <code>%a</code>, but print it like <code>%E</code> <code>%(FORMAT)T</code> output the date-time string resulting from using <code>FORMAT</code> as a format string for <code>strftime(3)</code>. The associated argument is the number of seconds since Epoch, or <code>-1</code> (current time) or <code>-2</code> (shell startup time). If no corresponding argument is supplies, the current time is used as default <code>%%</code> No conversion is done. Produces a <code>%</code> (percent sign) <p>Some of the mentioned format specifiers can modify their behaviour by getting a format modifier:</p>"},{"location":"commands/builtin/printf/#modifiers","title":"Modifiers","text":"<p>To be more flexible in the output of numbers and strings, the <code>printf</code> command allows format modifiers. These are specified between the introductory <code>%</code> and the character that specifies the format:</p> <pre><code>printf \"%50s\\n\" \"This field is 50 characters wide...\"\n</code></pre>"},{"location":"commands/builtin/printf/#field-and-printing-modifiers","title":"Field and printing modifiers","text":"Field output format <code>&lt;N&gt;</code> Any number: Specifies a minimum field width, if the text to print is shorter, it's padded with spaces, if the text is longer, the field is expanded <code>.</code> The dot: Together with a field width, the field is not expanded when the text is longer, the text is truncated instead. \"<code>%.s</code>\" is an undocumented equivalent for \"<code>%.0s</code>\", which will force a field width of zero, effectively hiding the field from output <code>*</code> The asterisk: the width is given as argument before the string or number. Usage (the \"<code>*</code>\" corresponds to the \"<code>20</code>\"): <code>printf \"%*s\\n\" 20 \"test string\"</code> <code>#</code> \"Alternative format\" for numbers: see table below <code>-</code> Left-bound text printing in the field (standard is right-bound) <code>0</code> Pads numbers with zeros, not spaces <code>&lt;space&gt;</code> Pad a positive number with a space, where a minus (<code>-</code>) is for negative numbers <code>+</code> Prints all numbers signed (<code>+</code> for positive, <code>-</code> for negative) <code>'</code> For decimal conversions, the thousands grouping separator is applied to the integer portion of the output according to the current LC_NUMERIC <p>The \"alternative format\" modifier <code>#</code>:</p> Alternative Format <code>%#o</code> The octal number is printed with a leading zero, unless it's zero itself <code>%#x</code>, <code>%#X</code> The hex number is printed with a leading \"<code>0x</code>\"/\"<code>0X</code>\", unless it's zero <code>%#g</code>, <code>%#G</code> The float number is printed with trailing zeros until the number of digits for the current precision is reached (usually trailing zeros are not printed) all number formats except <code>%d</code>, <code>%o</code>, <code>%x</code>, <code>%X</code> Always print a decimal point in the output, even if no digits follow it"},{"location":"commands/builtin/printf/#precision","title":"Precision","text":"<p>The precision for a floating- or double-number can be specified by using <code>.&lt;DIGITS&gt;</code>, where <code>&lt;DIGITS&gt;</code> is the number of digits for precision. If <code>&lt;DIGITS&gt;</code> is an asterisk (<code>*</code>), the precision is read from the argument that precedes the number to print, like (prints 4,3000000000):</p> <pre><code>printf \"%.*f\\n\" 10 4,3\n</code></pre> <p>The format <code>.*N</code> to specify the N'th argument for precision does not work in Bash.</p> <p>For strings, the precision specifies the maximum number of characters to print (i.e., the maximum field width). For integers, it specifies the number of digits to print (zero-padding!).</p>"},{"location":"commands/builtin/printf/#escape-codes","title":"Escape codes","text":"<p>These are interpreted if used anywhere in the format string, or in an argument corresponding to a <code>%b</code> format.</p> Code Description <code>\\\\</code> Prints the character <code>\\</code> (backslash) <code>\\a</code> Prints the alert character (ASCII code 7 decimal) <code>\\b</code> Prints a backspace <code>\\f</code> Prints a form-feed <code>\\n</code> Prints a newline <code>\\r</code> Prints a carriage-return <code>\\t</code> Prints a horizontal tabulator <code>\\v</code> Prints a vertical tabulator <code>\\\"</code> Prints a <code>'</code> <code>\\?</code> Prints a <code>?</code> <code>&lt;NNN&gt;</code> Interprets <code>&lt;NNN&gt;</code> as octal number and prints the corresponding character from the character set <code>\\0&lt;NNN&gt;</code> same as <code>&lt;NNN&gt;</code> <code>\\x&lt;NNN&gt;</code> Interprets <code>&lt;NNN&gt;</code> as hexadecimal number and prints the corresponding character from the character set (3 digits) <code>\\u&lt;NNNN&gt;</code> same as <code>\\x&lt;NNN&gt;</code>, but 4 digits <code>\\U&lt;NNNNNNNN&gt;</code> same as <code>\\x&lt;NNN&gt;</code>, but 8 digits <p>The following additional escape and extra rules apply only to arguments associated with a <code>%b</code> format:</p> Escape Rule Description <code>\\c</code> Terminate output similarly to the <code>\\c</code> escape used by <code>echo -e</code>. printf produces no additional output after coming across a <code>\\c</code> escape in a <code>%b</code> argument. <ul> <li>Backslashes in the escapes: <code>\\'</code>, <code>\\\"</code>, and <code>\\?</code> are not removed.</li> <li>Octal escapes beginning with <code>\\0</code> may contain up to four digits. (POSIX specifies up to three).</li> </ul> <p>These are also respects in which <code>%b</code> differs from the escapes used by \\$\\'...\\' style quoting.</p>"},{"location":"commands/builtin/printf/#examples","title":"Examples","text":""},{"location":"commands/builtin/printf/#snipplets","title":"Snipplets","text":"<ul> <li>print the decimal representation of a hexadecimal number (preserve the sign)<ul> <li><code>printf \"%d\\n\" 0x41</code></li> <li><code>printf \"%d\\n\" -0x41</code></li> <li><code>printf \"%+d\\n\" 0x41</code></li> </ul> </li> <li>print the octal representation of a decimal number<ul> <li><code>printf \"%o\\n\" 65</code></li> <li><code>printf \"%05o\\n\" 65</code> (5 characters width, padded with zeros)</li> </ul> </li> <li>this prints a 0, since no argument is specified<ul> <li><code>printf \"%d\\n\"</code></li> </ul> </li> <li>print the code number of the character <code>A</code><ul> <li><code>printf \"%d\\n\" \\'A</code></li> <li><code>printf \"%d\\n\" \"'A\"</code></li> </ul> </li> <li>Generate a greeting banner and assign it to the variable <code>GREETER</code><ul> <li><code>printf -v GREETER \"Hello %s\" \"$LOGNAME\"</code></li> </ul> </li> <li>Print a text at the end of the line, using <code>tput</code> to get the current line width<ul> <li><code>printf \"%*s\\n\" $(tput cols) \"Hello world!\"</code></li> </ul> </li> </ul>"},{"location":"commands/builtin/printf/#small-code-table","title":"Small code table","text":"<p>This small loop prints all numbers from 0 to 127 in</p> <ul> <li>decimal</li> <li>octal</li> <li>hex</li> </ul> <pre><code>for ((x=0; x &lt;= 127; x++)); do\n printf '%3d | %04o | 0x%02x\\n' \"$x\" \"$x\" \"$x\"\ndone\n</code></pre>"},{"location":"commands/builtin/printf/#ensure-well-formatted-mac-address","title":"Ensure well-formatted MAC address","text":"<p>This code here will take a common MAC address and rewrite it into a well-known format (regarding leading zeros or upper/lowercase of the hex digits, ...):</p> <pre><code>the_mac=\"0:13:ce:7:7a:ad\"\n\n# lowercase hex digits\nthe_mac=\"$(printf \"%02x:%02x:%02x:%02x:%02x:%02x\" 0x${the_mac//:/ 0x})\"\n\n# or the uppercase-digits variant\nthe_mac=\"$(printf \"%02X:%02X:%02X:%02X:%02X:%02X\" 0x${the_mac//:/ 0x})\"\n</code></pre>"},{"location":"commands/builtin/printf/#replacement-echo","title":"Replacement echo","text":"<p>This code was found in Solaris manpage for echo(1).</p> <p>Solaris version of <code>/usr/bin/echo</code> is equivalent to:</p> <pre><code>printf \"%b\\n\" \"$*\"\n</code></pre> <p>Solaris <code>/usr/ucb/echo</code> is equivalent to:</p> <pre><code>if [ \"X$1\" = \"X-n\" ]\nthen\n shift\n printf \"%s\" \"$*\"\nelse\n printf \"%s\\n\" \"$*\"\nfi\n</code></pre>"},{"location":"commands/builtin/printf/#prargs-implementation","title":"prargs Implementation","text":"<p>Working off the replacement echo, here is a terse implementation of prargs:</p> <pre><code>printf '\"%b\"\\n' \"$0\" \"$@\" | nl -v0 -s\": \"\n</code></pre>"},{"location":"commands/builtin/printf/#repeating-a-character-for-example-to-print-a-line","title":"repeating a character (for example to print a line)","text":"<p>A small trick: Combining printf and parameter expansion to draw a line</p> <pre><code>length=40\nprintf -v line '%*s' \"$length\"\necho ${line// /-}\n</code></pre> <p>or:</p> <pre><code>length=40\neval printf -v line '%.0s-' {1..$length}\n</code></pre>"},{"location":"commands/builtin/printf/#replacement-for-some-calls-to-date1","title":"Replacement for some calls to date(1)","text":"<p>The <code>%(...)T</code> format string is a direct interface to <code>strftime(3)</code>.</p> <pre><code>$ printf 'This is week %(%U/%Y)T.\\n' -1\nThis is week 52/2010.\n</code></pre> <p>Please read the manpage of <code>strftime(3)</code> to get more information about the supported formats.</p>"},{"location":"commands/builtin/printf/#differences-from-awk-printf","title":"differences from awk printf","text":"<p>Awk also derives its printf() function from C, and therefore has similar format specifiers. However, in all versions of awk the space character is used as a string concatenation operator, so it cannot be used as an argument separator. Arguments to awk printf must be separated by commas. Some versions of awk do not require printf arguments to be surrounded by parentheses, but you should use them anyway to provide portability.</p> <p>In the following example, the two strings are concatenated by the intervening space so that no argument remains to fill the format.</p> <pre><code>$ echo \"Foo\" | awk '{ printf \"%s\\n\" $1 }'\nawk: (FILENAME=- FNR=1) fatal: not enough arguments to satisfy format string\n `%s\nFoo'\n ^ ran out for this one\n</code></pre> <p>Simply replacing the space with a comma and adding parentheses yields correct awk syntax.</p> <pre><code>$ echo \"Foo\" | awk '{ printf( \"%s\\n\", $1 ) }'\nFoo\n</code></pre> <p>With appropriate metacharacter escaping the bash printf can be called from inside awk (as from perl and other languages that support shell callout) as long as you don't care about program efficiency or readability.</p> <pre><code>echo \"Foo\" | awk '{ system( \"printf \\\"%s\\\\n \\\" \\\"\" $1 \"\\\"\" ) }'\nFoo\n</code></pre>"},{"location":"commands/builtin/printf/#differences-from-c-and-portability-considerations","title":"Differences from C, and portability considerations","text":"<ul> <li> <p>The a, A, e, E, f, F, g, and G conversions are supported by Bash, but not required by POSIX.</p> </li> <li> <p>There is no wide-character support (wprintf). For instance, if you use <code>%c</code>, you're actually asking for the first byte of the argument. Likewise, the maximum field width modifier (dot) in combination with <code>%s</code> goes by bytes, not characters. This limits some of printf's functionality to working with ascii only. ksh93's <code>printf</code> supports the <code>L</code> modifier with <code>%s</code> and <code>%c</code> (but so far not <code>%S</code> or <code>%C</code>) in order to treat precision as character width, not byte count. zsh appears to adjust itself dynamically based upon <code>LANG</code> and <code>LC_CTYPE</code>. If <code>LC_CTYPE=C</code>, zsh will throw \"character not in range\" errors, and otherwise supports wide characters automatically if a variable-width encoding is set for the current locale.</p> </li> <li> <p>Bash recognizes and skips over any characters present in the length modifiers specified by POSIX during format string parsing.</p> </li> </ul> <p>builtins/printf.def<pre><code>#define LENMODS \"hjlLtz\"\n...\n/* skip possible format modifiers */\nmodstart = fmt;\nwhile (*fmt &amp;&amp; strchr (LENMODS, *fmt))\nfmt++;\n</code></pre> - mksh has no built-in printf by default (usually). There is an unsupported compile-time option to include a very poor, basically unusable implementation. For the most part you must rely upon the system's <code>/usr/bin/printf</code> or equivalent. The mksh maintainer recommends using <code>print</code>. The development version (post- R40f) adds a new parameter expansion in the form of <code>${name@Q}</code> which fills the role of <code>printf %q</code> -- expanding in a shell-escaped format.</p> <ul> <li>ksh93 optimizes builtins run from within a command substitution and which have no redirections to run in the shell's process. Therefore the <code>printf -v</code> functionality can be closely matched by <code>var=$(printf ...)</code> without a big performance hit.</li> </ul> <pre><code># Illustrates Bash-like behavior. Redefining printf is usually unnecessary / not recommended.\nfunction printf {\n case $1 in\n -v)\n shift\n nameref x=$1\n shift\n x=$(command printf \"$@\")\n ;;\n *)\n command printf \"$@\"\n esac\n}\nbuiltin cut\nprint $$\nprintf -v 'foo[2]' '%d\\n' \"$(cut -d ' ' -f 1 /proc/self/stat)\"\ntypeset -p foo\n# 22461\n# typeset -a foo=([2]=22461)\n</code></pre> <ul> <li>The optional Bash loadable <code>print</code> may be useful for ksh compatibility and to overcome some of echo's portability pitfalls. Bash, ksh93, and zsh's <code>print</code> have an <code>-f</code> option which takes a <code>printf</code> format string and applies it to the remaining arguments. Bash lists the synopsis as: <code>print: print [-Rnprs] [-u unit] [-f format] [arguments]</code>. However, only <code>-Rrnfu</code> are actually functional. Internally, <code>-p</code> is a noop (it doesn't tie in with Bash coprocs at all), and <code>-s</code> only sets a flag but has no effect. <code>-Cev</code> are unimplemented.</li> <li>Assigning to variables: The <code>printf -v</code> way is slightly different to the way using command-substitution. Command substitution removes trailing newlines before substituting the text, <code>printf -v</code> preserves all output.</li> </ul>"},{"location":"commands/builtin/printf/#see-also","title":"See also","text":"<ul> <li>SUS: printf utility and printf() function</li> <li>Code snip: Print a horizontal line uses some <code>printf</code> examples</li> <li>Greg's BashFAQ 18: How can I use numbers with leading zeros in a loop, e.g., 01, 02?</li> </ul>"},{"location":"commands/builtin/read/","title":"The read builtin command","text":"<p>read something about read here!</p>"},{"location":"commands/builtin/read/#synopsis","title":"Synopsis","text":"<pre><code>read [-ers] [-u &lt;FD&gt;] [-t &lt;TIMEOUT&gt;] [-p &lt;PROMPT&gt;] [-a &lt;ARRAY&gt;] [-n &lt;NCHARS&gt;] [-N &lt;NCHARS&gt;] [-d &lt;DELIM&gt;] [-i &lt;TEXT&gt;] [&lt;NAME...&gt;]\n</code></pre>"},{"location":"commands/builtin/read/#description","title":"Description","text":"<p>The <code>read</code> builtin reads one line of data (text, user input, ...) from standard input or a supplied filedescriptor number into one or more variables named by <code>&lt;NAME...&gt;</code>.</p> <p>Since Bash 4.3-alpha, <code>read</code> skips any <code>NUL</code> (ASCII code 0) characters in input.</p> <p>If <code>&lt;NAME...&gt;</code> is given, the line is word-split using IFS variable, and every word is assigned to one <code>&lt;NAME&gt;</code>. The remaining words are all assigned to the last <code>&lt;NAME&gt;</code> if more words than variable names are present.</p> <p>Info</p> <p>If no <code>&lt;NAME&gt;</code> is given, the whole line read (without performing word-splitting!) is assigned to the shell variable REPLY. Then, <code>REPLY</code> really contains the line as it was read, without stripping pre- and postfix spaces and other things!</p> <pre><code>while read -r; do\n printf '\"%s\"\\n' \"$REPLY\"\ndone &lt;&lt;&lt;\" a line with prefix and postfix space \"\n</code></pre> <p>If a timeout is given, or if the shell variable TMOUT is set, it is counted from initially waiting for input until the completion of input (i.e. until the complete line is read). That means the timeout can occur during input, too.</p>"},{"location":"commands/builtin/read/#options","title":"Options","text":"Option Description <code>-a &lt;ARRAY&gt;</code> read the data word-wise into the specified array <code>&lt;ARRAY&gt;</code> instead of normal variables <code>-d &lt;DELIM&gt;</code> recognize <code>&lt;DELIM&gt;</code> as data-end, rather than <code>&lt;newline&gt;</code> <code>-e</code> on interactive shells: use Bash's readline interface to read the data. Since version 5.1-alpha, this can also be used on specified file descriptors using <code>-u</code> <code>-i &lt;STRING&gt;</code> preloads the input buffer with text from <code>&lt;STRING&gt;</code>, only works when Readline (<code>-e</code>) is used <code>-n &lt;NCHARS&gt;</code> reads <code>&lt;NCHARS&gt;</code> characters of input, then quits <code>-N &lt;NCHARS&gt;</code> reads <code>&lt;NCHARS&gt;</code> characters of input, ignoring any delimiter, then quits <code>-p &lt;PROMPT&gt;</code> the prompt string <code>&lt;PROMPT&gt;</code> is output (without a trailing automatic newline) before the read is performed <code>-r</code> raw input - disables interpretion of backslash escapes and line-continuation in the read data <code>-s</code> secure input - don't echo input if on a terminal (passwords!) <code>-t &lt;TIMEOUT&gt;</code> wait for data <code>&lt;TIMEOUT&gt;</code> seconds, then quit (exit code 1). Fractional seconds (\"5.33\") are allowed since Bash 4. A value of 0 immediately returns and indicates if data is waiting in the exit code. Timeout is indicated by an exit code greater than 128. If timeout arrives before data is read completely (before end-of-line), the partial data is saved. <code>-u &lt;FD&gt;</code> use the filedescriptor number <code>&lt;FD&gt;</code> rather than <code>stdin</code> (0) <p>When both, <code>-a &lt;ARRAY&gt;</code> and a variable name <code>&lt;NAME&gt;</code> is given, then the array is set, but not the variable.</p> <p>Of course it's valid to set individual array elements without using <code>-a</code>:</p> <pre><code>read MYARRAY[5]\n</code></pre> <p>Warning</p> <p>Reading into array elements using the syntax above may cause pathname expansion to occur.</p> <p>Example: You are in a directory with a file named <code>x1</code>, and you want to read into an array <code>x</code>, index <code>1</code> with</p> <pre><code>read x[1]\n</code></pre> <p>then pathname expansion will expand to the filename <code>x1</code> and break your processing!</p> <p>Even worse, if <code>nullglob</code> is set, your array/index will disappear.</p> <p>To avoid this, either disable pathname expansion or quote the array name and index:</p> <pre><code>read 'x[1]'\n</code></pre>"},{"location":"commands/builtin/read/#return-status","title":"Return status","text":"Status Reason 0 no error 0 error when assigning to a read-only variable <sup>1</sup> 2 invalid option &gt;128 timeout (see <code>-t</code>) !=0 invalid filedescriptor supplied to <code>-u</code> !=0 end-of-file reached"},{"location":"commands/builtin/read/#read-without-r","title":"read without -r","text":"<p>Essentially all you need to know about <code>-r</code> is to ALWAYS use it. The exact behavior you get without <code>-r</code> is completely useless even for weird purposes. It basically allows the escaping of input which matches something in IFS, and also escapes line continuations. It's explained pretty well in the POSIX read spec.</p> <pre><code>2012-05-23 13:48:31 geirha it should only remove the backslashes, not change \\n and \\t and such into newlines and tabs\n2012-05-23 13:49:00 ormaaj so that's what read without -r does?\n2012-05-23 13:49:16 geirha no, -r doesn't remove the backslashes\n2012-05-23 13:49:34 ormaaj I thought read &lt;&lt;&lt;'str' was equivalent to read -r &lt;&lt;&lt;$'str'\n2012-05-23 13:49:38 geirha # read x y &lt;&lt;&lt; 'foo\\ bar baz'; echo \"&lt;$x&gt;&lt;$y&gt;\"\n2012-05-23 13:49:40 shbot geirha: &lt;foo bar&gt;&lt;baz&gt;\n2012-05-23 13:50:32 geirha no, read without -r is mostly pointless. Damn bourne\n2012-05-23 13:51:08 ormaaj So it's mostly (entirely) used to escape spaces\n2012-05-23 13:51:24 ormaaj and insert newlines\n2012-05-23 13:51:47 geirha ormaaj: you mostly get the same effect as using \\ at the prompt\n2012-05-23 13:52:04 geirha echo \\\" outputs a \" , read x &lt;&lt;&lt; '\\\"' reads a \"\n2012-05-23 13:52:32 ormaaj oh weird\n2012-05-23 13:52:46 * ormaaj struggles to think of a point to that...\n2012-05-23 13:53:01 geirha ormaaj: ask Bourne :P\n2012-05-23 13:53:20 geirha (not Jason)\n2012-05-23 13:53:56 ormaaj hm thanks anyway :)\n</code></pre>"},{"location":"commands/builtin/read/#examples","title":"Examples","text":""},{"location":"commands/builtin/read/#rudimentary-cat-replacement","title":"Rudimentary cat replacement","text":"<p>A rudimentary replacement for the <code>cat</code> command: read lines of input from a file and print them on the terminal.</p> <pre><code>opossum() {\n while read -r; do\n printf \"%s\\n\" \"$REPLY\"\n done &lt;\"$1\"\n}\n</code></pre> <p>Note: Here, <code>read -r</code> and the default <code>REPLY</code> is used, because we want to have the real literal line, without any mangeling. <code>printf</code> is used, because (depending on settings), <code>echo</code> may interpret some baskslash-escapes or switches (like <code>-n</code>).</p>"},{"location":"commands/builtin/read/#press-any-key","title":"Press any key...","text":"<p>Remember the MSDOS <code>pause</code> command? Here's something similar:</p> <pre><code>pause() {\n local dummy\n read -s -r -p \"Press any key to continue...\" -n 1 dummy\n}\n</code></pre> <p>Notes:</p> <ul> <li><code>-s</code> to suppress terminal echo (printing)</li> <li><code>-r</code> to not interpret special characters (like waiting for a second character if somebody presses the backslash)</li> </ul>"},{"location":"commands/builtin/read/#reading-columns","title":"Reading Columns","text":""},{"location":"commands/builtin/read/#simple-split","title":"Simple Split","text":"<p>Read can be used to split a string:</p> <pre><code>var=\"one two three\"\nread -r col1 col2 col3 &lt;&lt;&lt; \"$var\"\nprintf \"col1: %s col2: %s col3 %s\\n\" \"$col1\" \"$col2\" \"$col3\"\n</code></pre> <p>Take care that you cannot use a pipe:</p> <pre><code>echo \"$var\" | read col1 col2 col3 # does not work!\nprintf \"col1: %s col2: %s col3 %s\\n\" \"$col1\" \"$col2\" \"$col3\"\n</code></pre> <p>Why? because the commands of the pipe run in subshells that cannot modify the parent shell. As a result, the variables <code>col1</code>, <code>col2</code> and <code>col3</code> of the parent shell are not modified (see article: processtree).</p> <p>If the variable has more fields than there are variables, the last variable get the remaining of the line:</p> <pre><code>read col1 col2 col3 &lt;&lt;&lt; \"one two three four\"\nprintf \"%s\\n\" \"$col3\" #prints three four\n</code></pre>"},{"location":"commands/builtin/read/#changing-the-separator","title":"Changing The Separator","text":"<p>By default reads separates the line in fields using spaces or tabs. You can modify this using the special variable IFS, the Internal Field Separator.</p> <pre><code>IFS=\":\" read -r col1 col2 &lt;&lt;&lt; \"hello:world\"\nprintf \"col1: %s col2: %s\\n\" \"$col1\" \"$col2\"\n</code></pre> <p>Here we use the <code>var=value command</code> syntax to set the environment of <code>read</code> temporarily. We could have set <code>IFS</code> normally, but then we would have to take care to save its value and restore it afterward (<code>OLD=$IFS IFS=\":\"; read ....;IFS=$OLD</code>).</p> <p>The default <code>IFS</code> is special in that 2 fields can be separated by one or more space or tab. When you set <code>IFS</code> to something besides whitespace (space or tab), the fields are separated by exactly one character:</p> <pre><code>IFS=\":\" read -r col1 col2 col3 &lt;&lt;&lt; \"hello::world\"\nprintf \"col1: %s col2: %s col3 %s\\n\" \"$col1\" \"$col2\" \"$col3\"\n</code></pre> <p>See how the <code>::</code> in the middle infact defines an additional empty field.</p> <p>The fields are separated by exactly one character, but the character can be different between each field:</p> <pre><code>IFS=\":|@\" read -r col1 col2 col3 col4 &lt;&lt;&lt; \"hello:world|in@bash\"\nprintf \"col1: %s col2: %s col3 %s col4 %s\\n\" \"$col1\" \"$col2\" \"$col3\" \"$col4\"\n</code></pre>"},{"location":"commands/builtin/read/#are-you-sure","title":"Are you sure?","text":"<pre><code>asksure() {\necho -n \"Are you sure (Y/N)? \"\nwhile read -r -n 1 -s answer; do\n if [[ $answer = [YyNn] ]]; then\n [[ $answer = [Yy] ]] &amp;&amp; retval=0\n [[ $answer = [Nn] ]] &amp;&amp; retval=1\n break\n fi\ndone\n\necho # just a final linefeed, optics...\n\nreturn $retval\n}\n\n### using it\nif asksure; then\n echo \"Okay, performing rm -rf / then, master....\"\nelse\n echo \"Pfff...\"\nfi\n</code></pre>"},{"location":"commands/builtin/read/#ask-for-a-path-with-a-default-value","title":"Ask for a path with a default value","text":"<p>Note: The <code>-i</code> option was introduced with Bash 4</p> <pre><code>read -e -p \"Enter the path to the file: \" -i \"/usr/local/etc/\" FILEPATH\n</code></pre> <p>The user will be prompted, he can just accept the default, or edit it.</p>"},{"location":"commands/builtin/read/#multichar-ifs-parsing-a-simple-datetime-string","title":"Multichar-IFS: Parsing a simple date/time string","text":"<p>Here, <code>IFS</code> contains both, a colon and a space. The fields of the date/time string are recognized correctly.</p> <pre><code>datetime=\"2008:07:04 00:34:45\"\nIFS=\": \" read -r year month day hour minute second &lt;&lt;&lt; \"$datetime\"\n</code></pre>"},{"location":"commands/builtin/read/#portability-considerations","title":"Portability considerations","text":"<ul> <li>POSIX\u00ae only specified the <code>-r</code> option (raw read); <code>-r</code> is not only POSIX, you can find it in earlier Bourne source code</li> <li>POSIX\u00ae doesn't support arrays</li> <li><code>REPLY</code> is not POSIX\u00ae, you need to set <code>IFS</code> to the empty string to get the whole line for shells that don't know <code>REPLY</code>. <code>while IFS= read -r line; do ... done &lt; text.txt</code></li> </ul>"},{"location":"commands/builtin/read/#see-also","title":"See also","text":"<ul> <li>Internal: The printf builtin command</li> </ul> <ol> <li> <p>fixed in 4.2-rc1\u00a0\u21a9</p> </li> </ol>"},{"location":"commands/builtin/readonly/","title":"The readonly builtin command","text":""},{"location":"commands/builtin/readonly/#synopsis","title":"Synopsis","text":"<pre><code>readonly [-p] [-a] [-A] [-f] [NAME[=VALUE] ...]\n</code></pre>"},{"location":"commands/builtin/readonly/#description","title":"Description","text":"<p>The <code>readonly</code> builtin command is used to mark variables or functions as read-only, which means unchangeable. This implies that it can't be unset anymore. A <code>readonly</code> variable may not be redefined in child scopes. A readonly global may not be redefined as a function local variable. Simple command environment assignments may not reference readonly variables.</p>"},{"location":"commands/builtin/readonly/#options","title":"Options","text":"Option Description <code>-a</code> refer to normal arrays <code>-A</code> refer to associative arrays <code>-f</code> refer to functions <code>-p</code> print all read-only variables or functions, <code>-a</code>, <code>-A</code> and <code>-f</code> can be used to filter. The output is reusable as input <p>An argument of <code>--</code> disables further option processing.</p>"},{"location":"commands/builtin/readonly/#return-status","title":"Return status","text":"Status Reason 0 no error !=0 invalid option !=0 invalid combination of options !=0 a given <code>NAME</code> is invalid"},{"location":"commands/builtin/readonly/#examples","title":"Examples","text":""},{"location":"commands/builtin/readonly/#portability-considerations","title":"Portability considerations","text":"<ul> <li>in POSIX\u00ae, only the <code>-p</code> option is specified</li> </ul>"},{"location":"commands/builtin/readonly/#see-also","title":"See also","text":"<ul> <li>declare</li> <li>unset</li> </ul>"},{"location":"commands/builtin/return/","title":"The return builtin command","text":""},{"location":"commands/builtin/return/#synopsis","title":"Synopsis","text":"<pre><code>return [N]\n</code></pre>"},{"location":"commands/builtin/return/#description","title":"Description","text":"<p>The <code>return</code> command returns from a shell function.</p> <p>If <code>N</code> is given, the return code to the caller is set to <code>N</code>. If not, the returned status the the status of the most recently executed command (i.e. <code>$?</code>).</p>"},{"location":"commands/builtin/return/#options","title":"Options","text":"<p>There are no options.</p>"},{"location":"commands/builtin/return/#exit-status","title":"Exit status","text":"<p>If everything is okay, the <code>return</code> command doesn't come back. If it comes back, there was a problem in doing the return.</p> Status Reason 1 <code>return</code> was called while not being in a shell function or sourced file"},{"location":"commands/builtin/return/#examples","title":"Examples","text":""},{"location":"commands/builtin/return/#portability-considerations","title":"Portability considerations","text":""},{"location":"commands/builtin/return/#see-also","title":"See also","text":"<ul> <li>The exit builtin command</li> <li>The exit status</li> </ul>"},{"location":"commands/builtin/set/","title":"The set builtin command","text":"<p>FIXME</p> <p>incomplete text, examples, maybe extended description</p>"},{"location":"commands/builtin/set/#synopsis","title":"Synopsis","text":"<pre><code>set [--abefhkmnptuvxBCHP] &lt;-o OPTIONNAME&gt; [-][--] &lt;POSPARAMS&gt;\n</code></pre>"},{"location":"commands/builtin/set/#description","title":"Description","text":"<p><code>set</code> is primarily made to</p> <ul> <li>set the positional parameters (see handling positional parameters) to <code>&lt;POSPARAMS&gt;</code></li> <li>set shell attributes with short options (see below)</li> <li>set shell attributes with long option names (see below)</li> </ul> <p>Without any options, <code>set</code> displays all shell- and environment-variables (only is POSIX-mode) in a re-usable format <code>NAME=VALUE</code>.</p>"},{"location":"commands/builtin/set/#attributes","title":"Attributes","text":"<p>All attributes below can be switched on using <code>-X</code> and switched off using <code>+X</code>. This is done because of the historical meaning of the <code>-</code> to set flags (true for most commands on UNIX\u00ae).</p> Flag Optionname Description <code>-a</code> <code>allexport</code> Automatically mark new and altered variables to be exported to subsequent environments. <code>-b</code> <code>notify</code> Don't wait for the next prompt to print when showing the reports for a terminated background job (only with job control) <code>-e</code> <code>errexit</code> When set, the shell exits when a simple command in a command list exits non-zero (<code>FALSE</code>). This is not done in situations, where the exit code is already checked (<code>if</code>, <code>while</code>, <code>until</code>, <code>||</code>, <code>&amp;&amp;</code>) <code>-f</code> <code>noglob</code> Disable pathname expansion (globbing) <code>-h</code> <code>hashall</code> Remembers the location of commands when they're called (hashing). Enabled by default. <code>-k</code> <code>keyword</code> Allows to place environment-assignments everywhere in the commandline, not only infront of the called command. <code>-m</code> <code>monitor</code> Monitor mode. With job control, a short descriptive line is printed when a backgroud job ends. Default is \"on\" for interactive shells (with job control). <code>-n</code> <code>noexec</code> Read and parse but do not execute commands - useful for checking scripts for syntax errors. Ignored by interactive shells. <code>-o</code> Set/unset attributes with long option names, e.g. <code>set -o noglob</code>. The long option names are in the second column of this table. If no option name is given, all options are printed with their current status. <code>-p</code> <code>privileged</code> Turn on privileged mode. <code>-t</code> <code>onecmd</code> Exit after reading and executing one command. <code>-u</code> <code>nounset</code> Treat unset variables as an error when performing parameter expansion. Non-interactive shells exit on this error. <code>-v</code> <code>verbose</code> Print shell input lines as they are read - useful for debugging. <code>-x</code> <code>xtrace</code> Print commands just before execution - with all expansions and substitutions done, and words marked - useful for debugging. <code>-B</code> <code>braceexpand</code> The shell performs brace expansion This is on by default. <code>-C</code> <code>noclobber</code> Don't overwrite files on redirection operations. You can override that by specifying the <code>&gt;|</code> redirection operator when needed. See redirection <code>-E</code> <code>errtrace</code> <code>ERR</code>-traps are inherited by by shell functions, command substitutions, and commands executed in a subshell environment. <code>-H</code> <code>histexpand</code> Enable <code>!</code>-style history expansion. Defaults to <code>on</code> for interactive shells. <code>-P</code> <code>physical</code> Don't follow symlinks when changing directories - use the physical filesystem structure. <code>-T</code> <code>functrace</code> <code>DEBUG</code>- and <code>RETURN</code>-traps are inherited by subsequent environments, like <code>-E</code> for <code>ERR</code> trap. <code>-</code> \"End of options\" - all following arguments are assigned to the positional parameters, even when they begin with a dash. <code>-x</code> and <code>-v</code> options are turned off. Positional parameters are unchanged (unlike using <code>--</code>!) when no further arguments are given. <code>--</code> If no arguments follow, the positional parameters are unset. With arguments, the positional parameters are set, even if the strings begin with a <code>-</code> (dash) like an option. Long options usable with <code>-o</code> without a short equivalent <code>emacs</code> Use an emacs-style command line editing interface. This is enabled by default when the shell is interactive, unless the shell is started with <code>--noediting</code> option. <code>history</code> If set, command historization is done (enabled by default on interactive shells) <code>ignoreeof</code> The effect is as if the shell command <code>IGNOREEOF=10</code> had been executed. See shell variables. <code>nolog</code> (currently ignored) <code>pipefail</code> If set, the exit code from a pipeline is different from the normal (\"last command in pipeline\") behaviour: <code>TRUE</code> when no command failed, <code>FALSE</code> when something failed (code of the rightmost command that failed) <code>posix</code> When set, Bash runs in POSIX mode. <code>vi</code> Enables a <code>vi</code>-style command line editing interface."},{"location":"commands/builtin/set/#examples","title":"Examples","text":"<p>Tag a part of a shell script to output debugging information (<code>-x</code>):</p> <pre><code>#!/bin/bash\n...\nset -x # on\n...\nset +x # off\n...\n</code></pre>"},{"location":"commands/builtin/set/#portability-considerations","title":"Portability considerations","text":"<p><code>set</code> and its basic behaviour and options are specified by POSIX\u00ae. However, options that influence Bash-specific things are not portable, naturally.</p>"},{"location":"commands/builtin/set/#see-also","title":"See also","text":"<ul> <li>Internal: The shopt builtin command</li> </ul>"},{"location":"commands/builtin/shift/","title":"The shift builtin command","text":""},{"location":"commands/builtin/shift/#synopsis","title":"Synopsis","text":"<pre><code>shift [n]\n</code></pre>"},{"location":"commands/builtin/shift/#description","title":"Description","text":"<p>The <code>shift</code> builtin command is used to \"shift\" the positional parameters by the given number <code>n</code> or by 1, if no number is given.</p> <p>This means, the number and the position of the positional parameters are changed. The very first positional parameter is discarded, the second becomes the first one, etc.</p> <p>Imagine the following set of positional parameters (<code>$1</code> to <code>$4</code>):</p> Positional Parameter Value 1 This 2 is 3 a 4 test <p>When you use <code>shift 1</code>, they will be changed to:</p> Positional Parameter Value 1 is 2 a 3 test <p>The special parameter <code>$#</code> will reflect the final number of positional parameters.</p> <p>If the number given is 0, no changes are made to the positional parameters.</p>"},{"location":"commands/builtin/shift/#options","title":"Options","text":"<p>There are no options.</p>"},{"location":"commands/builtin/shift/#return-status","title":"Return status","text":"Status Reason 0 no error 1 non-numeric argument 1 given number (or the default 1) is bigger than the number of actually present positional parameters 1 given number is negative"},{"location":"commands/builtin/shift/#examples","title":"Examples","text":""},{"location":"commands/builtin/shift/#portability-considerations","title":"Portability considerations","text":"<ul> <li>The <code>shift</code> builtin command is specified by POSIX\u00ae.</li> <li> <p>Many shells will throw a fatal error when attempting to <code>shift</code> more than the number of positional parameters. POSIX does not require that behavior. Bash (even in POSIX mode) and Zsh return 1 when there are no args, and no error output is produced unless the shift_verbose shopt option is enabled. Ksh93, pdksh, posh, mksh, and dash, all throw useless fatal shell errors. <pre><code>$ dash -c 'f() { if shift; then echo \"$1\"; else echo \"no args\"; fi; }; f'\n dash: 1: shift: can't shift that many\n</code></pre> In most shells, you can work around this problem using the <code>command</code> builtin to suppress fatal errors caused by special builtins. <pre><code>$ dash -c 'f() { if command shift 2&gt;/dev/null; then echo \"$1\"; else echo \"no args\"; fi; }; f'\nno args\n</code></pre> While, POSIX requires this behavior, it isn't very obvious and some shells don't do it correctly. To work around this, you can use something like: <pre><code>$ mksh -c 'f() { if ! ${1+false} &amp;&amp; shift; then echo \"$1\"; else echo \"no args\"; fi; }; f'\nno args\n</code></pre> The mksh maintainer refuses to change either the <code>shift</code> or <code>command</code> builtins. Fixed. (Thanks!)</p> </li> <li> <p>Perhaps almost as bad as the above, busybox sh's <code>shift</code> always returns success, even when attempting to shift beyond the final argument. <pre><code>$ bb -c 'f() { if shift; then echo \"$1\"; else echo \"no args\"; fi; }; f'\n(no output)\n</code></pre> The above mksh workaround will work in this case too.</p> </li> </ul>"},{"location":"commands/builtin/shift/#see-also","title":"See also","text":""},{"location":"commands/builtin/shopt/","title":"The shopt builtin command","text":"<p>The <code>shopt</code> builtin manages shell options, a set of boolean (<code>on</code>/<code>off</code>) configuration variables that control the behaviour of the shell.</p>"},{"location":"commands/builtin/shopt/#synopsis","title":"Synopsis","text":"<pre><code>shopt [-pqsu] [-o] &lt;OPTNAME...&gt;\n</code></pre>"},{"location":"commands/builtin/shopt/#description","title":"Description","text":"<p>Note: Some of these options and other shell options can also be set with the set builtin.</p>"},{"location":"commands/builtin/shopt/#options","title":"Options","text":"Option Description <code>-o</code> Restrict the values of <code>&lt;OPTNAME...&gt;</code> to only those also known by the set builtin <code>-p</code> Print all shell options and their current value. Default. <code>-q</code> Quiet mode. Set exit code if named option is set. For multiple options: <code>TRUE</code> if all options are set, <code>FALSE</code> otherwise <code>-s</code> Enable (set) the shell options named by <code>&lt;OPTNAME...&gt;</code> or list all enabled options if no names are given <code>-u</code> Disabe (unset) the shell options named by <code>&lt;OPTNAME...&gt;</code> or list all disabled options if no names are given <p>As noted above, if only <code>-s</code> or <code>-u</code> are given without any option names, only the currently enabled (<code>-s</code>) or disabled (<code>-u</code>) options are printed.</p>"},{"location":"commands/builtin/shopt/#exit-code","title":"Exit code","text":"<p>When listing options, the exit code is <code>TRUE</code> (0), if all options are enabled, <code>FALSE</code> otherwise.</p> <p>When setting/unsetting an option, the exit code is <code>TRUE</code> unless the named option doesn't exitst.</p>"},{"location":"commands/builtin/shopt/#examples","title":"Examples","text":"<p>Enable the <code>nullglob</code> option:</p> <pre><code>shopt -s nullglob\n</code></pre>"},{"location":"commands/builtin/shopt/#portability-considerations","title":"Portability considerations","text":"<p>The <code>shopt</code> command is not portable accross different shells.</p>"},{"location":"commands/builtin/shopt/#see-also","title":"See also","text":"<ul> <li>Internal: The set builtin command</li> <li>Internal: List of shell options</li> </ul>"},{"location":"commands/builtin/trap/","title":"The trap builtin command","text":""},{"location":"commands/builtin/trap/#synopsis","title":"Synopsis","text":"<pre><code>trap [-lp] [[ARGUMENT] SIGNAL]\n</code></pre>"},{"location":"commands/builtin/trap/#description","title":"Description","text":"<p>The <code>trap</code> command is used to \"trap\" signals and other events. In this context, \"trapping\" means to install handler code.</p> <p>The shell code <code>ARGUMENT</code> is to be read and executed whenever the shell receives a signal or another event <code>SIGNAL</code>. The given <code>SIGNAL</code> specification can be</p> <ul> <li>the name of a signal with the SIG prefix, e.g. <code>SIGTERM</code></li> <li>the name of a signal without the SIG prefix, e.g. <code>TERM</code></li> <li>the number of a signal (see <code>trap -l</code>), e.g. <code>15</code></li> <li>the name or number of a special event (see table below), e.g. <code>EXIT</code></li> </ul> <p>Without any options or operands, <code>trap</code> prints a list of installed traps in a reusable format (equivalent to the <code>-p</code> option).</p> <p>Special <code>ARGUMENT</code>s</p> <ul> <li>if <code>ARGUMENT</code> is absent or <code>-</code> (dash), the signal/event handler is reset to its original value</li> <li>if <code>ARGUMENT</code> is the null string, the signal/event is ignored</li> </ul> <p>Special events</p> Name Code Description <code>EXIT</code> 0 executed on shell exit <code>DEBUG</code> executed before every simple command <code>RETURN</code> executed when a shell function or a sourced code finishes executing <code>ERR</code> executed each time a command's failure would cause the shell to exit when the <code>-e</code> option (<code>errexit</code>) is enabled"},{"location":"commands/builtin/trap/#options","title":"Options","text":"Option Description <code>-l</code> print a list of signal names and their corresponding numbers <code>-p</code> display the trap commands associated with each signal specification in a reusable format"},{"location":"commands/builtin/trap/#return-status","title":"Return status","text":"Status Reason 0 no error/success !=0 invalid option !=0 invalid signal specification"},{"location":"commands/builtin/trap/#examples","title":"Examples","text":""},{"location":"commands/builtin/trap/#list-installed-traps","title":"List installed traps","text":"<pre><code>trap\n</code></pre>"},{"location":"commands/builtin/trap/#ignore-terminal-interrupt-ctrl-c-sigint","title":"Ignore terminal interrupt (Ctrl-C, SIGINT)","text":"<pre><code>trap '' INT\n</code></pre>"},{"location":"commands/builtin/trap/#portability-considerations","title":"Portability considerations","text":"<ul> <li><code>trap</code> is specified by POSIX(R) without the <code>-l</code> and <code>-p</code> options</li> <li>in POSIX(R), beside signals, only <code>EXIT</code> (0) is valid as an event</li> </ul>"},{"location":"commands/builtin/trap/#see-also","title":"See also","text":"<ul> <li>the set command for the <code>-e</code> (<code>errexit</code>) option</li> </ul>"},{"location":"commands/builtin/unset/","title":"The unset builtin command","text":""},{"location":"commands/builtin/unset/#synopsis","title":"Synopsis","text":"<pre><code>unset [-f|v] [-n] [NAME ...]\n</code></pre>"},{"location":"commands/builtin/unset/#description","title":"Description","text":"<p>The <code>unset</code> builtin command is used to unset values and attributes of shell variables and functions. Without any option, <code>unset</code> tries to unset a variable first, then a function.</p>"},{"location":"commands/builtin/unset/#options","title":"Options","text":"Option Description <code>-f</code> treats each <code>NAME</code> as a function name <code>-v</code> treats each <code>NAME</code> as a variable name <code>-n</code> treats each <code>NAME</code> as a name reference and unsets the variable itself rather than the variable it references"},{"location":"commands/builtin/unset/#exit-status","title":"Exit status","text":"Status Reason 0 no error !=0 invalid option !=0 invalid combination of options (<code>-v</code> and <code>-f</code>) !=0 a given <code>NAME</code> is read-only"},{"location":"commands/builtin/unset/#examples","title":"Examples","text":"<pre><code>unset -v EDITOR\n\nunset -f myfunc1 myfunc2\n</code></pre>"},{"location":"commands/builtin/unset/#scope","title":"Scope","text":"<p>In bash, unset has some interesting properties due to its unique dynamic scope. If a local variable is both declared and unset (by calling unset on the local) from within the same function scope, then the variable appears unset to that scope and all child scopes until either returning from the function, or another local variable of the same name is declared underneath where the original variable was unset. In other words, the variable looks unset to everything until returning from the function in which the variable was set (and unset), at which point variables of the same name from higher scopes are uncovered and accessible once again.</p> <p>If however unset is called from a child scope relative to where a local variable has been set, then the variable of the same name in the next-outermost scope becomes visible to its scope and all children - as if the variable that was unset was never set to begin with. This property allows looking upwards through the stack as variable names are unset, so long as unset and the local it unsets aren't together in the same scope level.</p> <p>Here's a demonstration of this behavior.</p> <pre><code>#!/usr/bin/env bash\n\nFUNCNEST=10\n\n# Direct recursion depth.\n# Search up the stack for the first non-FUNCNAME[1] and count how deep we are.\ncallDepth() {\n # Strip \"main\" off the end of FUNCNAME[@] if current function is named \"main\" and\n # Bash added an extra \"main\" for non-interactive scripts.\n if [[ main == !(!(\"${FUNCNAME[1]}\")|!(\"${FUNCNAME[-1]}\")) &amp;&amp; $- != *i* ]]; then\n local -a 'fnames=(\"${FUNCNAME[@]:1:${#FUNCNAME[@]}-2}\")'\n else\n local -a 'fnames=(\"${FUNCNAME[@]:1}\")'\n fi\n\n if (( ! ${#fnames[@]} )); then\n printf 0\n return\n fi\n\n local n\n while [[ $fnames == ${fnames[++n]} ]]; do\n :\n done\n\n printf -- $n\n}\n\n# This function is the magic stack walker.\nunset2() {\n unset -v -- \"$@\"\n}\n\nf() {\n local a\n if (( (a=$(callDepth)) &lt;= 4 )); then\n (( a == 1 )) &amp;&amp; unset a\n (( a == 2 )) &amp;&amp; declare -g a='global scope yo'\n f\n else\n trap 'declare -p a' DEBUG\n unset2 a # declare -- a=\"5\"\n unset a a # declare -- a=\"4\"\n unset a # declare -- a=\"2\"\n unset a # ./unset-tests: line 44: declare: a: not found\n : # declare -- a=\"global scope yo\"\n fi\n}\n\na='global scope'\nf\n\n# vim: set fenc=utf-8 ff=unix ts=4 sts=4 sw=4 ft=sh nowrap et:\n</code></pre> <p>output:</p> <pre><code>declare -- a=\"5\"\ndeclare -- a=\"4\"\ndeclare -- a=\"2\"\n./unset-tests: line 44: declare: a: not found\ndeclare -- a=\"global scope yo\"\n</code></pre> <p>Some things to observe:</p> <ul> <li><code>unset2</code> is only really needed once. We remain 5 levels deep in <code>f</code>'s for the remaining <code>unset</code> calls, which peel away the outer layers of <code>a</code>'s.</li> <li>Notice that the \"a\" is unset using an ordinary unset command at recursion depth 1, and subsequently calling unset reveals a again in the global scope, which has since been modified in a lower scope using declare -g.</li> <li>Declaring a global with declare -g bypasses all locals and sets or modifies the variable of the global scope (outside of all functions). It has no affect on the visibility of the global.</li> <li>This doesn't apply to individual array elements. If two local arrays of the same name appear in different scopes, the entire array of the inner scope needs to be unset before any elements of the outer array become visible. This makes \"unset\" and \"unset2\" identical for individual array elements, and for arrays as a whole, unset and unset2 behave as they do for scalar variables.</li> </ul>"},{"location":"commands/builtin/unset/#args","title":"Args","text":"<p>Like several other Bash builtins that take parameter names, unset expands its arguments.</p> <pre><code> ~ $ ( a=({a..d}); unset 'a[2]'; declare -p a )\ndeclare -a a='([0]=\"a\" [1]=\"b\" [3]=\"d\")'\n</code></pre> <p>As usual in such cases, it's important to quote the args to avoid accidental results such as globbing.</p> <pre><code> ~ $ ( a=({a..d}) b=a c=d d=1; set -x; unset \"${b}[\"{2..3}-c\\]; declare -p a )\n+ unset 'a[2-1]' 'a[3-1]'\n+ declare -p a\ndeclare -a a='([0]=\"a\" [3]=\"d\")'\n</code></pre> <p>Of course hard to follow indirection is still possible whenever arithmetic is involved, also as shown above, even without extra expansions.</p> <p>In Bash, the <code>unset</code> builtin only evaluates array subscripts if the array itself is set.</p> <pre><code> ~ $ ( unset -v 'a[$(echo a was set &gt;&amp;2)0]' )\n ~ $ ( a=(); unset -v 'a[$(echo a was set &gt;&amp;2)0]' )\na was set\n</code></pre>"},{"location":"commands/builtin/unset/#portability-considerations","title":"Portability considerations","text":"<p>Quoting POSIX:</p> <pre><code>If neither -f nor -v is specified, name refers to a variable; if a variable by that name does not exist, it is unspecified whether a function by that name, if any, shall be unset.\n</code></pre> <p>Therefore, it is recommended to explicitly specify <code>-f</code> or <code>-v</code> when using <code>unset</code>. Also, I prefer it as a matter of style.</p>"},{"location":"commands/builtin/unset/#see-also","title":"See also","text":"<ul> <li>declare</li> <li>unset</li> <li>POSIX <code>unset</code> utility</li> </ul>"},{"location":"commands/builtin/wait/","title":"The wait builtin command","text":""},{"location":"commands/builtin/wait/#synopsis","title":"Synopsis","text":"<pre><code>wait [-f] [-n] [-p VARNAME] [ID...]\n</code></pre>"},{"location":"commands/builtin/wait/#description","title":"Description","text":"<p>The <code>wait</code> builtin command is used to wait for job completion and return exit status.</p> <ul> <li>if <code>ID</code> is a job specification, it waits for all processes in the pipeline of this job</li> <li>waits for a specific job (asynchronous command) and report its exit status if one or more <code>ID</code> is given</li> <li>waits for all running jobs (asynchronous commands)</li> <li>waits for \"the next\" job (<code>-n</code> option)</li> <li>waits for termination instead of status change (<code>-f</code> option)</li> </ul> <p><code>ID</code> may be an operating system process identifier or a shell job specification.</p>"},{"location":"commands/builtin/wait/#options","title":"Options","text":"Option Description <code>-n</code> Waits for \"the next\" child to exit (as opposed to \"all children\" without this option). Accepts a list of IDs (jobs) <code>-f</code> Waits for the termination of the given <code>ID</code> (instead of waiting for a status change only) <code>-p VARNAME</code> When waiting for a list (-n) or all jobs, writes the job ID to the job that was actually terminated into the variable <code>VARNAME</code>"},{"location":"commands/builtin/wait/#return-status","title":"Return status","text":"<p>The return status is the return status of the job waited for, or</p> Status Reason 0 waited for all jobs in shell's job list 1 the given <code>ID</code> is not a valid job or process ID"},{"location":"commands/builtin/wait/#examples","title":"Examples","text":""},{"location":"commands/builtin/wait/#portability-considerations","title":"Portability considerations","text":""},{"location":"commands/builtin/wait/#see-also","title":"See also","text":""},{"location":"dict/directory/","title":"Directory","text":"<p>In terms of UNIX\u00ae, a directory is a special file which contains a list of hardlinks to other files. These other files also can be directories of course, so it's possible to create a \\\"hierarchy of directories\\\" - the UNIX\u00ae-typical filesystem structure.</p> <p>The structure begins at the special directory <code>/</code> (root directory) and all other directory entries are subdirectories of it.</p>"},{"location":"dict/directory/#see-also","title":"See also","text":"<ul> <li>hardlink</li> <li>file</li> <li>special file</li> </ul>"},{"location":"dict/end_of_options/","title":"End of Options","text":"<p>The options of UNIX\u00ae utilities usually are introduced with a dash (<code>-</code>) character.</p> <p>This is problematic when a non-option argument has to be specified that begins with a dash. A common example for this are filenames.</p> <p>Many utilities use the convention to specify two consecutive dashes (<code>--</code>) to signal \\\"end of options at this point\\\". Beyond this tag, no options are processed anymore, even if an argument begins with a dash.</p> <p>Example: You want to list (<code>ls</code>) the file with the name <code>-hello</code>. With common option processing, this could end up in the ls-options <code>-h</code>, <code>-e</code>, <code>-l</code> and <code>-o</code> and probably in an error message about invalid options. You use this to avoid the wrong option processing:</p> <pre><code>ls -- -hello\n</code></pre> <p>POSIX\u00ae specifies that every utility should follow this rule (see ch. 12.2 Utility Syntax Guidelines), except</p> <ul> <li><code>echo</code> (historical reasons)</li> <li><code>test</code> (obvious parsing reasons)</li> </ul>"},{"location":"dict/end_of_options/#see-also","title":"See also","text":"<ul> <li>Scripting article, internal: getopts_tutorial</li> </ul>"},{"location":"dict/exit_status/","title":"Exit Status","text":"<ul> <li>exit code</li> <li>return status</li> </ul>"},{"location":"dict/exit_status/#purpose","title":"Purpose","text":"<p>The exit status is a numeric value that is returned by a program to the calling program or shell. In C programs, this is represented by the return value of the <code>main()</code> function or the value you give to <code>exit(3)</code>. The only part of the number that matters are the least significant 8 bits, which means there are only values from 0 to 255.</p> <p>In the shell, every operation generates an exit status (return status), even if no program is called. An example for such an operation is a redirection.</p> <p>The parameter to the</p> <ul> <li><code>exit</code> (exit the shell/script)</li> <li><code>return</code> (return from a function)</li> </ul> <p>builtin commands serve the purpose of giving the exit status to the calling component.</p> <p>This - and only this - makes it possible to determinate the success or failure of an operation. For scripting, always set exit codes.</p>"},{"location":"dict/exit_status/#values","title":"Values","text":"<p>The code is a number between 0 and 255, where the part from 126 to 255 is reserved to be used by the Bash shell directly or for special purposes, like reporting a termination by a signal:</p> Code Description 0 success 1-255 failure (in general) 126 the requested command (file) can't be executed (but was found) 127 command (file) not found 128 according to ABS it's used to report an invalid argument to the exit builtin, but I wasn't able to verify that in the source code of Bash (see code 255) 128+N the shell was terminated by the signal N (also used like this by various other programs) 255 wrong argument to the exit builtin (see code 128) <p>The lower codes 0 to 125 are not reserved and may be used for whatever the program likes to report. A value of 0 means successful termination, a value not 0 means unsuccessful termination. This behavior (== 0, != 0) is also what Bash reacts on in some code flow control statements like <code>if</code> or <code>while</code>.</p>"},{"location":"dict/exit_status/#portability","title":"Portability","text":"<p>Tables of shell behavior involving non-portable side-effects or common bugs with exit statuses. Note heirloom doesn't support pipeline negation (<code>! pipeline</code>).</p>"},{"location":"dict/exit_status/#misc","title":"Misc","text":"test bash 4.2.45 bash (POSIX) zsh 5.0.2 (emulate ksh) ksh93 93v- 2013-03-18 mksh R44 2013/02/24 posh 0.11 dash 0.5.7.3 busybox 1.2.1 heirloom 050706 <pre>:; : `false` `echo $? &gt;&amp;2`</pre> 1 1 1 1 0 0 0 0 1 <pre>false; eval; echo $?</pre> 0 0 0 0 0 1 0 1 0 <pre>x=`false` eval echo $?</pre> 1 1 1 1 0 0 0 0 1 <pre>eval echo \\$? &lt;&amp;0`false`</pre> 1 1 1 1 0 0 0 0 1 <pre>while :; do ! break; done; echo $?</pre> 1 1 1 1 0 0 1 1 - <pre>false; :\necho $?discussion\n1\n1\n1\n0\n1\n1\n1\n1\n\n\n<pre>(exit 2); for x in \"`exit 3`\"; do echo $?; done</pre>\n3\n3\n3\n3\n2\n2\n0\n0\n3"},{"location":"dict/exit_status/#functions","title":"functions","text":"<p>Measuring side-effects during the function call, during return, and\ntransparency of the return builtin.</p>\n\n\n\ntest\nbash\nbash(POSIX)\nzsh(emulate ksh)\nksh93\nmksh\nposh\ndash\nbusybox\nheirloom\n\n\n\n\n<pre>f() { echo $?; }; :; f `false`</pre>\n1\n1\n1\n1\n0\n0\n0\n0\n1\n\n\n<pre>f() { return; }; false; f; echo $?</pre>\n1\n1\n1\n0\n1\n1\n1\n1\n1\n\n\n<pre>f() { return $?; }; false; f; echo $?</pre>\n1\n1\n1\n1\n1\n1\n1\n1\n1\n\n\n<pre>f() { ! return; }; f; echo $?</pre>\n0\n0\n1\n0\n0\n0\n1\n1\n-\n\n\n<pre>f() { ! return; }; false; f; echo $?</pre>\n1\n1\n0\n0\n1\n1\n0\n0\n-\n\n\n<pre>f() { return; }; x=`false` f; echo $?</pre>\n1\n1\n1\n1\n0\n0\n0\n0\n0\n\n\n<pre>f() { return; }; f &lt;&amp;0`false`; echo $?</pre>\n1\n1\n1\n1\n0\n0\n0\n0\n1\n\n\n<pre>f() { x=`false` return; }; f; echo $?</pre>\n1\n1\n1\n0\n0\n0\n0\n0\n1\n\n\n<pre>f() { return &lt;&amp;0`false`; }; f; echo $?</pre>\n1\n1\n1\n0\n0\n0\n0\n0\n1\n\n\n<pre>f() { x=`false` return &lt;&amp;0`false`; }; f; echo $?</pre>\n1\n1\n1\n1\n0\n0\n0\n0\n1"},{"location":"dict/exit_status/#caseesac","title":"case..esac","text":"<p>Statuses measured within the command and after, with matching and\nnon-matching patterns.</p>\n\n\n\ntest\nbash\nbash(POSIX)\nzsh(emulate ksh)\nksh93\nmksh\nposh\ndash\nbusybox\nheirloom\n\n\n\n\n<pre>(exit 2); case x in x) echo $?;; esac</pre>\n2\n2\n0\n2\n2\n2\n0\n0\n2\n\n\n<pre> (exit 2); case `exit 3`x in x) echo $?;; esac</pre>\n3\n3\n0\n3\n2\n2\n0\n0\n3\n\n\n<pre> (exit 2); case x in `exit 4`x) echo $?;; esac</pre>\n4\n4\n4\n4\n2\n2\n0\n0\n4\n\n\n<pre> (exit 2); case `exit 3`x in `exit 4`x) echo $?;; esac</pre>\n4\n4\n4\n4\n2\n2\n0\n0\n4\n\n\n<pre>(exit 2); case x in x);; esac; echo $?</pre>\n0\n0\n0\n0\n0\n0\n0\n0\n2\n\n\n<pre>(exit 2); case x in \"\");; esac; echo $?</pre>\n0\n0\n0\n0\n0\n0\n0\n0\n2\n\n\n<pre>(exit 2); case `exit 3`x in x);; esac; echo $?</pre>\n0\n0\n0\n3\n0\n0\n0\n0\n3\n\n\n<pre>(exit 2); case `exit 3`x in \"\");; esac; echo $?</pre>\n0\n0\n0\n3\n0\n0\n0\n0\n3\n\n\n<pre>(exit 2); case x in `exit 4`x);; esac; echo $?</pre>\n0\n0\n0\n4\n0\n0\n0\n0\n4\n\n\n<pre>(exit 2); case x in `exit 4`);; esac; echo $?</pre>\n0\n0\n4\n4\n0\n0\n0\n0\n4\n\n\n<pre>(exit 2); case `exit 3`x in `exit 4`);; esac; echo $?</pre>\n0\n0\n4\n4\n0\n0\n0\n0\n4\n\n\n<pre> (exit 2); case `exit 3`x in `exit 4`x);; esac; echo $?</pre>\n0\n0\n0\n4\n0\n0\n0\n0\n4"},{"location":"dict/file/","title":"File","text":"<p>A file is a pool of data in the <code>filesystem</code>. On userlevel, it's referenced using a name, a hardlink to the file.</p> <p>If a file is not referenced anymore (number of hardlinks to it drops to 1) then the space allocated for that file is re-used, unless it's still used by some process.</p> <p>The file-data splits into actual payload (file contents) and some metadata like filesize, filemode or timestamps. The metadata is stored in the <code>inode</code>.</p> <p>Strictly spoken, a hardlink (also called \\\"filename\\\") points to the <code>inode</code> which organizes a file, not to the file itself.</p>"},{"location":"dict/file/#see-also","title":"See also","text":"<ul> <li>filetimes</li> <li>hardlink</li> </ul>"},{"location":"dict/filetimes/","title":"File timestamp","text":""},{"location":"dict/filetimes/#atime","title":"atime","text":"<p>This timestamp indicates when a file was last accessed (read). <code>cat</code>ing a file or executing a shellscript will set it, for example.</p>"},{"location":"dict/filetimes/#ctime","title":"ctime","text":"<p>This timestamp is set, whenever the metadata of a file (stored in the responsible inode) is set. The metadata includes for example:</p> <ul> <li>file name</li> <li>fize size</li> <li>file mode (permissions)</li> </ul> <p>and some other things. <code>ctime</code> will also be updated when a file is written to (when <code>mtime</code> is updated.</p>"},{"location":"dict/filetimes/#mtime","title":"mtime","text":"<p>The mtime is set, whenever a file's contents are changed, for example by editing a file.</p>"},{"location":"dict/globbing/","title":"Globbing","text":"<p>Globbing is the procedure of</p> <ul> <li>matching all filenames against a given pattern</li> <li>expanding to all matching filenames</li> </ul> <p>Unlike MSDOS, where the called program had to interpret the patterns, the globbing on UNIX\u00ae is done by the shell, the matched filenames are given as parameters to a called command:</p> <pre><code>$ cat *.txt\n</code></pre> <p>really executes</p> <pre><code>$ cat 1.txt 3.txt foobar.txt XXX.txt\n</code></pre> <p>The term \\\"glob\\\" originates back in the UNIX\u00ae days where an executable <code>glob</code> (from \\\"global\\\") existed which was used to expand pattern-matching characters. Later, this functionality was built into the shell. There's still a library function called <code>glob()</code> (POSIX\u00ae), which serves the same purpose.</p>"},{"location":"dict/globbing/#see-also","title":"See also","text":"<ul> <li>shell</li> <li>hardlink</li> </ul>"},{"location":"dict/globbing/#see-also-article","title":"See also (article)","text":"<ul> <li>pathname expansion</li> </ul>"},{"location":"dict/hardlink/","title":"Hardlink","text":"<p>Also the article for:</p> <ul> <li>filename</li> </ul> <p>A hardlink associates a filename with a file. That name is an entry in a directory listing. Of course a file can have more hardlinks to it (usually the number of hardlinks to a file is limited), but all hardlinks to a file must reside on the same <code>filesystem</code> as the file itself!</p> <p>What you usually call a file is just a name for that file, and thus, a hardlink.</p> <p>The difference between a symbolic link and a hard link is that there is no easy way to differentiate between a \\'real\\' file and a hard link, let's take a look at the example:</p> <p>* create an empty file</p> <pre><code>$ touch a\n</code></pre> <p>* create a hard link \\'b\\' and sym link \\'c\\' to empty file</p> <pre><code>$ ln a b\n$ ln -s a c\n</code></pre> <p>as you can see file(1) can't differentiate between a real file \\'a\\' and a hard link \\'b\\', but it can tell \\'c\\' is a sym link</p> <pre><code>$ file *\na: empty\nb: empty\nc: symbolic link to `a'\n</code></pre> <p><code>ls -i</code> prints out the inode numbers of files, if two files have the same inode number AND are on the same file system it means they are hardlinked.</p> <pre><code>$ ls -i *\n5262 a 5262 b 5263 c\n</code></pre> <p>hard links don't consume additional space on the filesystem, the space is freed when the last hard link pointing to it is deleted.</p>"},{"location":"dict/hardlink/#see-also","title":"See also","text":"<ul> <li>file</li> <li>symlink</li> </ul>"},{"location":"dict/interpreter_directive/","title":"Interpreter Directive","text":"<ul> <li>shebang</li> </ul> <p>The interpreter directive, usually called shebang, is the character sequence starting with <code>#!</code> (hash, exclamation-point) at the beginning of the very first line of an executable text file on unixoid operating systems.</p> <p>The program loader of the operating system may use this line to load an interpreter for this file when executed. This makes it a self-executable script.</p> <p>A shebang will typically look like</p> <pre><code>#!/bin/bash\n</code></pre> <p>Since the line starting with <code>#</code> is a comment for the shell (and some other scripting languages), it's ignored.</p> <p>Regarding the shebang, there are various, differences between operating systems, including:</p> <ul> <li>may require a space after <code>#!</code> and before the pathname of the interpreter</li> <li>may be able to take arguments for the interpreter</li> <li>...</li> </ul> <p>POSIX\u00ae doesn't specify the shebang, though in general it's commonly supported by operating systems.</p>"},{"location":"dict/interpreter_directive/#see-also","title":"See also","text":"<ul> <li>#!-magic - a nice overview of the differences between various operating systems</li> </ul>"},{"location":"dict/parameter/","title":"Parameter","text":"<p>Also the article for: variable, positional parameter, special parameter</p> <p>In Bash, a parameter is simply an entity that stores values and can be referenced. Depending on the type, the parameters can be set directly, only indirectly, or only automatically by the shell.</p> <p>Bash knows 3 types of parameters:</p> <ul> <li>variables</li> <li>positional parameters</li> <li>special parameters</li> </ul>"},{"location":"dict/parameter/#variables","title":"variables","text":"<p>A shell variable is a parameter denoted by a variable name:</p> <ul> <li>containing only alphanumeric characters and underscores</li> <li>beginning with an alphabetic character or an underscore</li> </ul> <p>A value can be assigned to a variable, using the variable's name and an equal-sign:</p> <pre><code>NAME=VALUE\n</code></pre> <p>Once a variable is set, it exists and can only be unset by the <code>unset</code> builtin command.</p> <p>The nullstring is a valid value:</p> <pre><code>NAME=\nNAME=\"\"\n</code></pre>"},{"location":"dict/parameter/#positional-parameters","title":"positional parameters","text":"<p>A positional parameter is denoted by a number other than <code>0</code> (zero).</p> <p>Positional parameters reflect the shell's arguments that are not given to the shell itself (in practise, the script arguments, also the function arguments). You can't directly assign to the positional parameters, however, the set builtin command can be used to indirectly set them.</p> <p>The first to ninth positional parameter is referenced by <code>$1</code> to <code>$9</code>. All following positional parameters (tenth and above) must be referenced by the number given in curly braces, i.e., <code>${10}</code> or <code>${432}</code>.</p> <p>Unlike popular belief, <code>$0</code> is not a positional parameter.</p> <p>See also the scripting article about handling positional parameters.</p>"},{"location":"dict/parameter/#special-parameters","title":"special parameters","text":"<p>There are a bunch of special parameters, which are set by the shell. Direct assignment to them is not possible. These parameter names are formed of one character.</p> <p>Please see shellvars.</p>"},{"location":"dict/parameter/#see-also","title":"See also","text":"<ul> <li>Syntax article, internal: pe</li> <li>Syntax article, internal: shellvars</li> <li>Scripting article, internal: posparams</li> </ul>"},{"location":"dict/posix/","title":"POSIX","text":"<p>POSIX\u00ae is a family of standards defined by the IEEE to give a minimum API and interface standardization across the variants of UNIX\u00ae operating systems.</p> <p>One part of it is the standardization of minimum functionality and behaviour of the system shell and some utilities (commands).</p> <ul> <li>UNIX is a registered trademark of The Open Group in the US and other countries.</li> <li>POSIX is a registered trademark of the IEEE Inc.</li> </ul>"},{"location":"dict/posix/#see-also","title":"See also","text":"<ul> <li>Dictionary, internal: shell</li> </ul>"},{"location":"dict/shell/","title":"Shell","text":"<p>On UNIX\u00ae, the shell is the main interaction tool between the user-level and the system. That doesn't necessarily mean the user always sits infront of a shell, but it's integral part of the system, not only an \\\"optional commandline interpreter\\\".</p> <p>The main job of a shell is to execute commands as a user requests them. This behaviour alone doesn't help much. A shell knits some intelligence and flow control around the possibility to execute commands - it's a complete commandline-oriented user-interface (UI).</p> <p>FIXME</p> <p>tbd.</p>"},{"location":"dict/shell/#see-also","title":"See also","text":""},{"location":"dict/shell/#see-also-external","title":"See also (external)","text":"<ul> <li>Wikipedia: UNIX shell</li> </ul>"},{"location":"dict/special_file/","title":"Special file","text":"<p>Unlike a regular file (a bunch of accessible data organized on a filesystem), it's a special filename that points to a ressource or similar:</p> <ul> <li>character special files</li> <li>block special files</li> <li>named pipes</li> <li>socket files</li> </ul> <p>Since a directory also is only a file, you can count it as special file, too.</p>"},{"location":"dict/special_file/#see-also","title":"See also","text":"<ul> <li>file</li> <li>filename</li> <li>directory</li> </ul>"},{"location":"dict/symlink/","title":"Symlink","text":"<p>A symlink (symbolic link) is a \\\"normal\\\" file, which contains a pointer to another filename. Since it really only points to another filename it can</p> <ul> <li>reference filenames on other filesystems</li> <li>reference filenames that don't actually exist</li> <li>save a reference to the name of a directory</li> </ul>"},{"location":"dict/symlink/#see-also","title":"See also","text":"<ul> <li>hardlink</li> <li>directory</li> </ul>"},{"location":"howto/calculate-dc/","title":"Calculating with dc","text":"","tags":["bash","shell","scripting","arithmetic","calculate"]},{"location":"howto/calculate-dc/#introduction","title":"Introduction","text":"<p>dc(1) is a non standard, but commonly found, reverse-polish Desk Calculator. According to Ken Thompson, \"dc is the oldest language on Unix; it was written on the PDP-7 and ported to the PDP-11 before Unix [itself] was ported\".</p> <p>Historically the standard bc(1) has been implemented as a front-end to dc.</p>","tags":["bash","shell","scripting","arithmetic","calculate"]},{"location":"howto/calculate-dc/#simple-calculation","title":"Simple calculation","text":"<p>In brief, the reverse polish notation means the numbers are put on the stack first, then an operation is applied to them. Instead of writing <code>1+1</code>, you write <code>1 1+</code>.</p> <p>By default <code>dc</code>, unlike <code>bc</code>, doesn't print anything, the result is pushed on the stack. You have to use the \"p\" command to print the element at the top of the stack. Thus a simple operation looks like:</p> <pre><code>$ dc &lt;&lt;&lt; '1 1+pq'\n2\n</code></pre> <p>I used a \"here string\" present in bash 3.x, ksh93 and zsh. if your shell doesn't support this, you can use <code>echo '1 1+p' | dc</code> or if you have GNU <code>dc</code>, you can use <code>dc -e '1 1 +p'</code>.</p> <p>Of course, you can also just run <code>dc</code> and enter the commands.</p> <p>The classic operations are:</p> <ul> <li>addition: <code>+</code></li> <li>subtraction: <code>-</code></li> <li>division: <code>/</code></li> <li>multiplication: <code>*</code></li> <li>remainder (modulo): <code>%</code></li> <li>exponentiation: <code>^</code></li> <li>square root: <code>v</code></li> </ul> <p>GNU <code>dc</code> adds a couple more.</p> <p>To input a negative number you need to use the <code>_</code> (underscore) character:</p> <pre><code>$ dc &lt;&lt;&lt; '1_1-p'\n2\n</code></pre> <p>You can use the digits <code>0</code> to <code>9</code> and the letters <code>A</code> to <code>F</code> as numbers, and a dot (<code>.</code>) as a decimal point. The <code>A</code> to <code>F</code> must be capital letters in order not to be confused with the commands specified with lower case characters. A number with a letter is considered hexadecimal:</p> <pre><code>dc &lt;&lt;&lt; 'Ap'\n10\n</code></pre> <p>The output is converted to base 10 by default</p>","tags":["bash","shell","scripting","arithmetic","calculate"]},{"location":"howto/calculate-dc/#scale-and-base","title":"Scale And Base","text":"<p><code>dc</code> is a calulator with abitrary precision, by default this precision is 0. thus <code>dc &lt;&lt;&lt; \"5 4/p\"</code> prints \"1\".</p> <p>We can increase the precision using the <code>k</code> command. It pops the value at the top of the stack and uses it as the precision argument:</p> <pre><code>dc &lt;&lt;&lt; '2k5 4/p' # prints 1.25\ndc &lt;&lt;&lt; '4k5 4/p' # prints 1.2500\ndc &lt;&lt;&lt; '100k 2vp'\n1.4142135623730950488016887242096980785696718753769480731766797379907\\\n324784621070388503875343276415727\n</code></pre> <p>dc supports large precision arguments.</p> <p>You can change the base used to output (print) the numbers with <code>o</code> and the base used to input (type) the numbers with <code>i</code>:</p> <pre><code>dc &lt;&lt; EOF\n20 p# prints 20, output is in base 10\n16o # the output is now in base 2 16\n20p # prints 14, in hex\n16i # the output is now in hex\np # prints 14 this doesn't modify the number in the stack\n10p # prints 10 the output is done in base 16\nEOF\n</code></pre> <p>Note: when the input value is modified, the base is modified for all commands, including <code>i</code>:</p> <pre><code>dc &lt;&lt; EOF\n16i 16o # base is 16 for input and output\n10p # prints 10\n10i # ! set the base to 10 i.e. to 16 decimal\n17p # prints 17\nEOF\n</code></pre> <p>This code prints 17 while we might think that <code>10i</code> reverts the base back to 10 and thus the number should be converted to hex and printed as 11. The problem is 10 was typed while the input base 16, thus the base was set to 10 hexadecimal, i.e. 16 decimal.</p> <pre><code>dc &lt;&lt; EOF\n16o16o10p #prints 10\nAi # set the base to A in hex i.e. 10\n17p # prints 11 in base 16\nEOF\n</code></pre>","tags":["bash","shell","scripting","arithmetic","calculate"]},{"location":"howto/calculate-dc/#stack","title":"Stack","text":"<p>There are two basic commands to manipulate the stack:</p> <ul> <li><code>d</code> duplicates the top of the stack</li> <li> <p><code>c</code> clears the stack</p> <p>$ dc &lt;&lt; EOF 2 # put 2 on the stack d # duplicate i.e. put another 2 on the stack *p # multiply and print c p # clear and print EOF 4 dc: stack empty</p> </li> </ul> <p><code>c p</code> results in an error, as we would expect, as c removes everything on the stack. Note: we can use <code>#</code> to put comments in the script.</p> <p>If you are lost, you can inspect (i.e. print) the stack using the command <code>f</code>. The stack remains unchanged:</p> <pre><code>dc &lt;&lt;&lt; '1 2 d 4+f'\n6\n2\n1\n</code></pre> <p>Note how the first element that will be popped from the stack is printed first, if you are used to an HP calculator, it's the reverse.</p> <p>Don't hesitate to put <code>f</code> in the examples of this tutorial, it doesn't change the result, and it's a good way to see what's going on.</p>","tags":["bash","shell","scripting","arithmetic","calculate"]},{"location":"howto/calculate-dc/#registers","title":"Registers","text":"<p>The GNU <code>dc</code> manual says that dc has at least 256 registers depending on the range of unsigned char. I\\'m not sure how you are supposed to use the NUL byte. Using a register is easy:</p> <pre><code>dc &lt;&lt;EOF\n12 # put 12 on the stack\nsa # remove it from the stack (s), and put it in register 'a'\n10 # put 10 on the stack\nla # read (l) the value of register 'a' and push it on the stack\n+p # add the 2 values and print\nEOF\n</code></pre> <p>The above snippet uses newlines to embed comments, but it doesn't really matter, you can use <code>echo '12sa10la+p'| dc</code>, with the same results.</p> <p>The register can contain more than just a value, each register is a stack on its own.</p> <pre><code>dc &lt;&lt;EOF\n12sa #store 12 in 'a'\n6Sa # with a capital S the 6 is removed\n # from the main stack and pushed on the 'a' stack\nlap # prints 6, the value at the top of the 'a' stack\nlap # still prints 6\nLap # prints 6 also but with a capital L, it pushes the value in 'a'\n # to the main stack and pulls it from the 'a' stack\nlap # prints 12, which is now at the top of the stack\nEOF\n</code></pre>","tags":["bash","shell","scripting","arithmetic","calculate"]},{"location":"howto/calculate-dc/#macros","title":"Macros","text":"<p><code>dc</code> lets you push arbitrary strings on the stack when the strings are enclosed in <code>[]</code>. You can print it with <code>p</code>: <code>dc &lt;&lt;&lt; '[Hello World!]p'</code> and you can evalute it with x: <code>dc &lt;&lt;&lt; '[1 2+]xp'</code>.</p> <p>This is not that interesting until combined with registers. First, let's say we want to calculate the square of a number (don't forget to include <code>f</code> if you get lost!):</p> <pre><code>dc &lt;&lt; EOF\n3 # push our number on the stack\nd # duplicate it i.e. push 3 on the stack again\nd**p # duplicate again and calculate the product and print\nEOF\n</code></pre> <p>Now we have several cubes to calculate, we could use <code>dd**</code> several times, or use a macro.</p> <pre><code>dc &lt;&lt; EOF\n[dd**] # push a string\nsa # save it in register a\n3 # push 3 on the stack\nlax # push the string \"dd**\" on the stack and execute it\np # print the result\n4laxp # same operation for 4, in one line\nEOF\n</code></pre>","tags":["bash","shell","scripting","arithmetic","calculate"]},{"location":"howto/calculate-dc/#conditionals-and-loops","title":"Conditionals and Loops","text":"<p><code>dc</code> can execute a macro stored in a register using the <code>lR x</code> combo, but it can also execute macros conditionally. <code>&gt;a</code> will execute the macro stored in the register <code>a</code>, if the top of the stack is greater than the second element of the stack. Note: the top of the stack contains the last entry. When written, it appears as the reverse of what we are used to reading:</p> <pre><code>dc &lt;&lt; EOF\n[[Hello World]p] sR # store in 'R' a macro that prints Hello World\n2 1 &gt;R # do nothing 1 is at the top 2 is the second element\n1 2 &gt;R # prints Hello World\nEOF\n</code></pre> <p>Some <code>dc</code> have <code>&gt;R &lt;R =R</code>, GNU <code>dc</code> had some more, check your manual. Note that the test \"consumes\" its operands: the 2 first elements are popped off the stack (you can verify that <code>dc &lt;&lt;&lt; \"[f]sR 2 1 &gt;R 1 2 &gt;R f\"</code> doesn't print anything)</p> <p>Have you noticed how we can include a macro (string) in a macro? and as <code>dc</code> relies on a stack we can, in fact, use the macro recursively (have your favorite control-c key combo ready ;)) :</p> <pre><code>dc &lt;&lt; EOF\n[ [Hello World] p # our macro starts by printing Hello World\n lRx ] # and then executes the macro in R\nsR # we store it in the register R\nlRx # and finally executes it.\nEOF\n</code></pre> <p>We have recursivity, we have test, we have loops:</p> <pre><code>dc &lt;&lt; EOF\n[ li # put our index i on the stack\n p # print it, to see what's going on\n 1 - # we decrement the index by one\n si # store decremented index (i=i-1)\n 0 li &gt;L # if i &gt; 0 then execute L\n] sL # store our macro with the name L\n\n10 si # let's give to our index the value 10\nlLx # and start our loop\nEOF\n</code></pre> <p>Of course code written this way is far too easy to read! Make sure to remove all those extra spaces newlines and comments:</p> <pre><code>dc &lt;&lt;&lt; '[lip1-si0li&gt;L]sL10silLx'\ndc &lt;&lt;&lt; '[p1-d0&lt;L]sL10lLx' # use the stack instead of a register\n</code></pre> <p>I'll let you figure out the second example, it's not hard, it uses the stack instead of a register for the index.</p>","tags":["bash","shell","scripting","arithmetic","calculate"]},{"location":"howto/calculate-dc/#next","title":"Next","text":"<p>Check your dc manual, i haven't decribed everything, like arrays (only documented with \"; : are used by bc(1) for array operations\" on solaris, probably because echo \\'1 0:a 0Sa 2 0:a La 0;ap\\' | dc results in //Segmentation Fault (core dump) //, the latest solaris uses GNU dc)</p> <p>You can find more info and dc programs here:</p> <ul> <li>http://en.wikipedia.org/wiki/Dc_(Unix)</li> </ul> <p>And more example, as well as a dc implementation in python here:</p> <ul> <li>http://en.literateprograms.org/Category:Programming_language:dc</li> <li>http://en.literateprograms.org/Desk_calculator_%28Python%29</li> </ul> <p>The manual for the 1971 dc from Bell Labs:</p> <ul> <li>http://cm.bell-labs.com/cm/cs/who/dmr/man12.ps (dead link)</li> </ul>","tags":["bash","shell","scripting","arithmetic","calculate"]},{"location":"howto/collapsing_functions/","title":"Collapsing Functions","text":"","tags":["bash","shell","scripting","example","function","collapse"]},{"location":"howto/collapsing_functions/#what-is-a-collapsing-function","title":"What is a \"Collapsing Function\"?","text":"<p>A collapsing function is a function whose behavior changes depending upon the circumstances under which it's run. Function collapsing is useful when you find yourself repeatedly checking a variable whose value never changes.</p>","tags":["bash","shell","scripting","example","function","collapse"]},{"location":"howto/collapsing_functions/#how-do-i-make-a-function-collapse","title":"How do I make a function collapse?","text":"<p>Function collapsing requires some static feature in the environment. A common example is a script that gives the user the option of having \"verbose\" output.</p> <pre><code>#!/bin/bash\n\n[[ $1 = -v || $1 = --verbose ]] &amp;&amp; verbose=1\n\nchatter() {\n if [[ $verbose ]]; then\n chatter() {\n echo \"$@\"\n }\n chatter \"$@\"\n else\n chatter() {\n :\n }\n fi\n}\n\necho \"Waiting for 10 seconds.\"\nfor i in {1..10}; do\n chatter \"$i\"\n sleep 1\ndone\n</code></pre>","tags":["bash","shell","scripting","example","function","collapse"]},{"location":"howto/collapsing_functions/#how-does-it-work","title":"How does it work?","text":"<p>The first time you run chatter(), the function redefines itself based on the value of verbose. Thereafter, chatter doesn't check <code>$verbose</code>, it simply is. Further calls to the function reflect its collapsed nature. If verbose is unset, chatter will echo nothing, with no extra effort from the developer.</p>","tags":["bash","shell","scripting","example","function","collapse"]},{"location":"howto/collapsing_functions/#more-examples","title":"More examples","text":"<p>FIXME</p> <p>Add more examples!</p> <pre><code># Somewhat more portable find -executable\n# FIXME/UNTESTED (I don't have access to all of the different versions of find.)\n# Usage: find PATH ARGS -- use find like normal, except use -executable instead of\n# various versions of -perm /+ blah blah and hacks\nfind() {\n hash find || { echo 'find not found!'; exit 1; }\n # We can be pretty sure \"$0\" should be executable.\n if [[ $(command find \"$0\" -executable 2&gt; /dev/null) ]]; then\n unset -f find # We can just use the command find\n elif [[ $(command find \"$0\" -perm /u+x 2&gt; /dev/null) ]]; then\n find() {\n typeset arg args\n for arg do\n [[ $arg = -executable ]] &amp;&amp; args+=(-perm /u+x) || args+=(\"$arg\")\n done\n command find \"${args[@]}\"\n }\n elif [[ $(command find \"$0\" -perm +u+x 2&gt; /dev/null) ]]; then\n find() {\n typeset arg args\n for arg do\n [[ $arg = -executable ]] &amp;&amp; args+=(-perm +u+x) || args+=(\"$arg\")\n done\n command find \"${args[@]}\"\n }\n else # Last resort\n find() {\n typeset arg args\n for arg do\n [[ $arg = -executable ]] &amp;&amp; args+=(-exec test -x {} \\; -print) || args+=(\"$arg\")\n done\n command find \"${args[@]}\"\n }\n fi\n find \"$@\"\n}\n</code></pre> <pre><code>#!/bin/bash\n# Using collapsing functions to turn debug messages on/off\n\n[ \"--debug\" = \"$1\" ] &amp;&amp; dbg=echo || dbg=:\n\n\n# From now on if you use $dbg instead of echo, you can select if messages will be shown\n\n$dbg \"This message will only be displayed if --debug is specified at the command line\n</code></pre>","tags":["bash","shell","scripting","example","function","collapse"]},{"location":"howto/conffile/","title":"Config files for your script","text":"","tags":["bash","shell","scripting","config","files","include","configuration"]},{"location":"howto/conffile/#general","title":"General","text":"<p>For this task, you don't have to write large parser routines (unless you want it 100% secure or you want a special file syntax) - you can use the Bash source command. The file to be sourced should be formated in key=\"value\" format, otherwise bash will try to interpret commands:</p> <pre><code>#!/bin/bash\necho \"Reading config....\" &gt;&amp;2\nsource /etc/cool.cfg\necho \"Config for the username: $cool_username\" &gt;&amp;2\necho \"Config for the target host: $cool_host\" &gt;&amp;2\n</code></pre> <p>So, where do these variables come from? If everything works fine, they are defined in /etc/cool.cfg which is a file that's sourced into the current script or shell. Note: this is not the same as executing this file as a script! The sourced file most likely contains something like:</p> <pre><code>cool_username=\"guest\"\ncool_host=\"foo.example.com\"\n</code></pre> <p>These are normal statements understood by Bash, nothing special. Of course (and, a big disadvantage under normal circumstances) the sourced file can contain everything that Bash understands, including malicious code!</p> <p>The <code>source</code> command also is available under the name <code>.</code> (dot). The usage of the dot is identical:</p> <pre><code>#!/bin/bash\necho \"Reading config....\" &gt;&amp;2\n. /etc/cool.cfg #note the space between the dot and the leading slash of /etc.cfg\necho \"Config for the username: $cool_username\" &gt;&amp;2\necho \"Config for the target host: $cool_host\" &gt;&amp;2\n</code></pre>","tags":["bash","shell","scripting","config","files","include","configuration"]},{"location":"howto/conffile/#per-user-configs","title":"Per-user configs","text":"<p>There's also a way to provide a system-wide config file in /etc and a custom config in ~/(user's home) to override system-wide defaults. In the following example, the if/then construct is used to check for the existance of a user-specific config:</p> <pre><code>#!/bin/bash\necho \"Reading system-wide config....\" &gt;&amp;2\n. /etc/cool.cfg\nif [ -r ~/.coolrc ]; then\n echo \"Reading user config....\" &gt;&amp;2\n . ~/.coolrc\nfi\n</code></pre>","tags":["bash","shell","scripting","config","files","include","configuration"]},{"location":"howto/conffile/#secure-it","title":"Secure it","text":"<p>As mentioned earlier, the sourced file can contain anything a Bash script can. Essentially, it is an included Bash script. That creates security issues. A malicicios person can \"execute\" arbitrary code when your script is sourcing its config file. You might want to allow only constructs in the form <code>NAME=VALUE</code> in that file (variable assignment syntax) and maybe comments (though technically, comments are unimportant). Imagine the following \"config file\", containing some malicious code:</p> <pre><code># cool config file for my even cooler script\nusername=god_only_knows\nhostname=www.example.com\npassword=secret ; echo rm -rf ~/*\nparameter=foobar &amp;&amp; echo \"You've bene pwned!\";\n# hey look, weird code follows...\necho \"I am the skull virus...\"\necho rm -fr ~/*\nmailto=netadmin@example.com\n</code></pre> <p>You don't want these <code>echo</code>-commands (which could be any other commands!) to be executed. One way to be a bit safer is to filter only the constructs you want, write the filtered results to a new file and source the new file. We also need to be sure something nefarious hasn't been added to the end of one of our name=value parameters, perhaps using ; or &amp;&amp; command separators. In those cases, perhaps it is simplest to just ignore the line entirely. Egrep (<code>grep -E</code>) will help us here, it filters by description:</p> <pre><code>#!/bin/bash\nconfigfile='/etc/cool.cfg'\nconfigfile_secured='/tmp/cool.cfg'\n\n# check if the file contains something we don't want\nif egrep -q -v '^#|^[^ ]*=[^;]*' \"$configfile\"; then\n echo \"Config file is unclean, cleaning it...\" &gt;&amp;2\n # filter the original to a new file\n egrep '^#|^[^ ]*=[^;&amp;]*' \"$configfile\" &gt; \"$configfile_secured\"\n configfile=\"$configfile_secured\"\nfi\n\n# now source it, either the original or the filtered variant\nsource \"$configfile\"\n</code></pre> <p>To make clear what it does: egrep checks if the file contains something we don't want, if yes, egrep filters the file and writes the filtered contents to a new file. If done, the original file name is changed to the name stored in the variable <code>configfile</code>. The file named by that variable is sourced, as if it were the original file.</p> <p>This filter allows only <code>NAME=VALUE</code> and comments in the file, but it doesn't prevent all methods of code execution. I will address that later.</p>","tags":["bash","shell","scripting","config","files","include","configuration"]},{"location":"howto/dissectabadoneliner/","title":"Dissect a bad oneliner","text":"<pre><code>$ ls *.zip | while read i; do j=`echo $i | sed 's/.zip//g'`; mkdir $j; cd $j; unzip ../$i; cd ..; done\n</code></pre> <p>This is an actual one-liner someone asked about in <code>#bash</code>. There are several things wrong with it. Let's break it down!</p> <pre><code>$ ls *.zip | while read i; do ...; done\n</code></pre> <p>(Please read http://mywiki.wooledge.org/ParsingLs.) This command executes <code>ls</code> on the expansion of <code>*.zip</code>. Assuming there are filenames in the current directory that end in '.zip', ls will give a human-readable list of those names. The output of ls is not for parsing. But in sh and bash alike, we can loop safely over the glob itself:</p> <pre><code>$ for i in *.zip; do j=`echo $i | sed 's/.zip//g'`; mkdir $j; cd $j; unzip ../$i; cd ..; done\n</code></pre> <p>Let's break it down some more!</p> <pre><code>j=`echo $i | sed 's/.zip//g'` # where $i is some name ending in '.zip'\n</code></pre> <p>The goal here seems to be get the filename without its <code>.zip</code> extension. In fact, there is a POSIX\u00ae-compliant command to do this: <code>basename</code> The implementation here is suboptimal in several ways, but the only thing that's genuinely error-prone with this is \"<code>echo $i</code>\". Echoing an unquoted variable means wordsplitting will take place, so any whitespace in <code>$i</code> will essentially be normalized. In <code>sh</code> it is necessary to use an external command and a subshell to achieve the goal, but we can eliminate the pipe (subshells, external commands, and pipes carry extra overhead when they launch, so they can really hurt performance in a loop). Just for good measure, let's use the more readable, modern <code>$()</code> construct instead of the old style backticks:</p> <pre><code>sh $ for i in *.zip; do j=$(basename \"$i\" \".zip\"); mkdir $j; cd $j; unzip ../$i; cd ..; done\n</code></pre> <p>In Bash we don't need the subshell or the external basename command. See Substring removal with parameter expansion:</p> <pre><code>bash $ for i in *.zip; do j=\"${i%.zip}\"; mkdir $j; cd $j; unzip ../$i; cd ..; done\n</code></pre> <p>Let's keep going:</p> <pre><code>$ mkdir $j; cd $j; ...; cd ..\n</code></pre> <p>As a programmer, you never know the situation under which your program will run. Even if you do, the following best practice will never hurt: When a following command depends on the success of a previous command(s), check for success! You can do this with the \"<code>&amp;&amp;</code>\" conjunction, that way, if the previous command fails, bash will not try to execute the following command(s). It's fully POSIX\u00ae. Oh, and remember what I said about wordsplitting in the previous step? Well, if you don't quote <code>$j</code>, wordsplitting can happen again.</p> <pre><code>$ mkdir \"$j\" &amp;&amp; cd \"$j\" &amp;&amp; ... &amp;&amp; cd ..\n</code></pre> <p>That's almost right, but there's one problem -- what happens if <code>$j</code> contains a slash? Then <code>cd ..</code> will not return to the original directory. That's wrong! <code>cd -</code> causes cd to return to the previous working directory, so it's a much better choice:</p> <pre><code>$ mkdir \"$j\" &amp;&amp; cd \"$j\" &amp;&amp; ... &amp;&amp; cd -\n</code></pre> <p>(If it occurred to you that I forgot to check for success after cd -, good job! You could do this with <code>{ cd - || break; }</code>, but I'm going to leave that out because it's verbose and I think it's likely that we will be able to get back to our original working directory without a problem.)</p> <p>So now we have:</p> <pre><code>sh $ for i in *.zip; do j=$(basename \"$i\" \".zip\"); mkdir \"$j\" &amp;&amp; cd \"$j\" &amp;&amp; unzip ../$i &amp;&amp; cd -; done\n</code></pre> <pre><code>bash $ for i in *.zip; do j=\"${i%.zip}\"; mkdir \"$j\" &amp;&amp; cd \"$j\" &amp;&amp; unzip ../$i &amp;&amp; cd -; done\n</code></pre> <p>Let's throw the <code>unzip</code> command back in the mix:</p> <pre><code>mkdir \"$j\" &amp;&amp; cd \"$j\" &amp;&amp; unzip ../$i &amp;&amp; cd -\n</code></pre> <p>Well, besides word splitting, there's nothing terribly wrong with this. Still, did it occur to you that unzip might already be able to target a directory? There isn't a standard for the <code>unzip</code> command, but all the implementations I've seen can do it with the -d flag. So we can drop the cd commands entirely:</p> <pre><code>$ mkdir \"$j\" &amp;&amp; unzip -d \"$j\" \"$i\"\n</code></pre> <pre><code>sh $ for i in *.zip; do j=$(basename \"$i\" \".zip\"); mkdir \"$j\" &amp;&amp; unzip -d \"$j\" \"$i\"; done\n</code></pre> <pre><code>bash $ for i in *.zip; do j=\"${i%.zip}\"; mkdir \"$j\" &amp;&amp; unzip -d \"$j\" \"$i\"; done\n</code></pre> <p>There! That's as good as it gets.</p>"},{"location":"howto/edit-ed/","title":"Editing files via scripts with ed","text":"","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#why-ed","title":"Why ed?","text":"<p>Like <code>sed</code>, <code>ed</code> is a line editor. However, if you try to change file contents with <code>sed</code>, and the file is open elsewhere and read by some process, you will find out that GNU <code>sed</code> and its <code>-i</code> option will not allow you to edit the file. There are circumstances where you may need that, e.g. editing active and open files, the lack of GNU, or other <code>sed</code>, with \"in-place\" option available.</p> <p>Why <code>ed</code>?</p> <ul> <li>maybe your <code>sed</code> doesn't support in-place edit</li> <li>maybe you need to be as portable as possible</li> <li>maybe you need to really edit in-file (and not create a new file like GNU <code>sed</code>)</li> <li>last but not least: standard <code>ed</code> has very good editing and addressing possibilities, compared to standard <code>sed</code></li> </ul> <p>Don't get me wrong, this is not meant as anti-<code>sed</code> article! It's just meant to show you another way to do the job.</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#commanding-ed","title":"Commanding ed","text":"<p>Since <code>ed</code> is an interactive text editor, it reads and executes commands that come from <code>stdin</code>. There are several ways to feed our commands to ed:</p> <p>Pipelines</p> <pre><code>echo '&lt;ED-COMMANDS&gt;' | ed &lt;FILE&gt;\n</code></pre> <p>To inject the needed newlines, etc. it may be easier to use the builtin command, <code>printf</code> (\"help printf\"). Shown here as an example Bash function to prefix text to file content:</p> <pre><code># insertHead \"$text\" \"$file\"\n\ninsertHead() {\n printf '%s\\n' H 1i \"$1\" . w | ed -s \"$2\"\n}\n</code></pre> <p>Here-strings</p> <pre><code>ed &lt;FILE&gt; &lt;&lt;&lt; '&lt;ED-COMMANDS&gt;'\n</code></pre> <p>Here-documents</p> <pre><code>ed &lt;FILE&gt; &lt;&lt;EOF\n&lt;ED-COMMANDS&gt;\nEOF\n</code></pre> <p>Which one you prefer is your choice. I will use the here-strings, since it looks best here IMHO.</p> <p>There are other ways to provide input to <code>ed</code>. For example, process substitution. But these should be enough for daily needs.</p> <p>Since <code>ed</code> wants commands separated by newlines, I'll use a special Bash quoting method, the C-like strings <code>$'TEXT'</code>, as it can interpret a set of various escape sequences and special characters. I'll use the <code>-s</code> option to make it less verbose.</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#the-basic-interface","title":"The basic interface","text":"<p>Check the <code>ed</code> manpage for details</p> <p>Similar to <code>vi</code> or <code>vim</code>, <code>ed</code> has a \"command mode\" and an \"interactive mode\". For non-interactive use, the command mode is the usual choice.</p> <p>Commands to <code>ed</code> have a simple and regular structure: zero, one, or two addresses followed by a single-character command, possibly followed by parameters to that command. These addresses specify one or more lines in the text buffer. Every command that requires addresses has default addresses, so the addresses can often be omitted.</p> <p>The line addressing is relative to the current line. If the edit buffer is not empty, the initial value for the current line shall be the last line in the edit buffer, otherwise zero. Generally, the current line is the last line affected by a command. All addresses can only address single lines, not blocks of lines!</p> <p>Line addresses or commands using regular expressions interpret POSIX Basic Regular Expressions (BRE). A null BRE is used to reference the most recently used BRE. Since <code>ed</code> addressing is only for single lines, no RE can ever match a newline.</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#debugging-your-ed-scripts","title":"Debugging your ed scripts","text":"<p>By default, <code>ed</code> is not very talkative and will simply print a \"?\" when an error occurs. Interactively you can use the <code>h</code> command to get a short message explaining the last error. You can also turn on a mode that makes <code>ed</code> automatically print this message with the <code>H</code> command. It is a good idea to always add this command at the beginning of your ed scripts:</p> <pre><code>bash &gt; ed -s file &lt;&lt;&lt; $'H\\n,df'\n?\nscript, line 2: Invalid command suffix\n</code></pre> <p>While working on your script, you might make errors and destroy your file, you might be tempted to try your script doing something like:</p> <pre><code># Works, but there is better\n\n# copy my original file\ncp file file.test\n\n# try my script on the file\ned -s file.test &lt;&lt;&lt; $'H\\n&lt;ed commands&gt;\\nw'\n\n# see the results\ncat file.test\n</code></pre> <p>There is a much better way though, you can use the ed command <code>p</code> to print the file, now your testing would look like:</p> <pre><code>ed -s file &lt;&lt;&lt; $'H\\n&lt;ed commands&gt;\\n,p'\n</code></pre> <p>the <code>,</code> (comma) in front of the <code>p</code> command is a shortcut for <code>1,$</code> which defines an address range for the first to the last line, <code>,p</code> thus means print the whole file, after it has been modified. When your script runs sucessfully, you only have to replace the <code>,p</code> by a <code>w</code>.</p> <p>Of course, even if the file is not modified by the <code>p</code> command, it's always a good idea to have a backup copy!</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#editing-your-files","title":"Editing your files","text":"<p>Most of these things can be done with <code>sed</code>. But there are also things that can't be done in <code>sed</code> or can only be done with very complex code.</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#simple-word-substitutions","title":"Simple word substitutions","text":"<p>Like <code>sed</code>, <code>ed</code> also knows the common <code>s/FROM/TO/</code> command, and it can also take line-addresses. If no substitution is made on the addressed lines, it's considered an error.</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#substitutions-through-the-whole-file","title":"Substitutions through the whole file","text":"<pre><code>ed -s test.txt &lt;&lt;&lt; $',s/Windows(R)-compatible/POSIX-conform/g\\nw'\n</code></pre> <p>Note: The comma as single address operator is an alias for <code>1,$</code> (\"all lines\").</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#substitutions-in-specific-lines","title":"Substitutions in specific lines","text":"<p>On a line containing <code>fruits</code>, do the substitution:</p> <pre><code>ed -s test.txt &lt;&lt;&lt; $'/fruits/s/apple/banana/g\\nw'\n</code></pre> <p>On the 5<sup>th</sup> line after the line containing <code>fruits</code>, do the substitution:</p> <pre><code>ed -s test.txt &lt;&lt;&lt; $'/fruits/+5s/apple/banana/g\\nw'\n</code></pre>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#block-operations","title":"Block operations","text":"","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#delete-a-block-of-text","title":"Delete a block of text","text":"<p>The simple one is a well-known (by position) block of text:</p> <pre><code># delete lines number 2 to 4 (2, 3, 4)\ned -s test.txt &lt;&lt;&lt; $'2,5d\\nw'\n</code></pre> <p>This deletes all lines matching a specific regular expression:</p> <pre><code># delete all lines matching foobar\ned -s test.txt &lt;&lt;&lt; $'g/foobar/d\\nw'\n</code></pre> <p>g/regexp/ applies the command following it to all the lines matching the regexp</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#move-a-block-of-text","title":"Move a block of text","text":"<p>...using the <code>m</code> command: <code>&lt;ADDRESS&gt; m &lt;TARGET-ADDRESS&gt;</code></p> <p>This is definitely something that can't be done easily with sed.</p> <pre><code># moving lines 5-9 to the end of the file\ned -s test.txt &lt;&lt;&lt; $'5,9m$\\nw'\n\n# moving lines 5-9 to line 3\ned -s test.txt &lt;&lt;&lt; $'5,9m3\\nw'\n</code></pre>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#copy-a-block-of-text","title":"Copy a block of text","text":"<p>...using the <code>t</code> command: <code>&lt;ADDRESS&gt; t &lt;TARGET-ADDRESS&gt;</code></p> <p>You use the <code>t</code> command just like you use the <code>m</code> (move) command.</p> <pre><code># make a copy of lines 5-9 and place it at the end of the file\ned -s test.txt &lt;&lt;&lt; $'5,9t$\\nw'\n\n# make a copy of lines 5-9 and place it at line 3\ned -s test.txt &lt;&lt;&lt; $'5,9t3\\nw'\n</code></pre>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#join-all-lines","title":"Join all lines","text":"<p>...but leave the final newline intact. This is done by an extra command: <code>j</code> (join).</p> <pre><code>ed -s file &lt;&lt;&lt; $'1,$j\\nw'\n</code></pre> <p>Compared with two other methods (using <code>tr</code> or <code>sed</code>), you don't have to delete all newlines and manually add one at the end.</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#file-operations","title":"File operations","text":"","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#insert-another-file","title":"Insert another file","text":"<p>How do you insert another file? As with <code>sed</code>, you use the <code>r</code> (read) command. That inserts another file at the line before the last line (and prints the result to stdout - <code>,p</code>):</p> <pre><code>ed -s FILE1 &lt;&lt;&lt; $'$-1 r FILE2\\n,p'\n</code></pre> <p>To compare, here's a possible <code>sed</code> solution which must use Bash arithmetic and the external program <code>wc</code>:</p> <pre><code>sed \"$(($(wc -l &lt; FILE1)-1))r FILE2\" FILE1\n\n# UPDATE here's one which uses GNU sed's \"e\" parameter for the s-command\n# it executes the commands found in pattern space. I'll take that as a\n# security risk, but well, sometimes GNU &gt; security, you know...\nsed '${h;s/.*/cat FILE2/e;G}' FILE1\n</code></pre> <p>Another approach, in two invocations of sed, that avoids the use of external commands completely:</p> <pre><code>sed $'${s/$/\\\\n-||-/;r FILE2\\n}' FILE1 | sed '0,/-||-/{//!h;N;//D};$G'\n</code></pre>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#pitfalls","title":"Pitfalls","text":"","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#ed-is-not-sed","title":"ed is not sed","text":"<p>ed and sed might look similar, but the same command(s) might act differently:</p> <p>__ /foo/d __</p> <p>In sed /foo/d will delete all lines matching foo, in ed the commands are not repeated on each line so this command will search the next line matching foo and delete it. If you want to delete all lines matching foo, or do a subsitution on all lines matching foo you have to tell ed about it with the g (global) command:</p> <pre><code>echo $'1\\n1\\n3' &gt; file\n\n#replace all lines matching 1 by \"replacement\"\ned -s file &lt;&lt;&lt; $'g/1/s/1/replacement/\\n,p'\n\n#replace the first line matching 1 by \"replacement\"\n#(because it starts searching from the last line)\ned -s file &lt;&lt;&lt; $'s/1/replacement/\\n,p'\n</code></pre> <p>__ an error stops the script __</p> <p>You might think that it's not a problem and that the same thing happens with sed and you're right, with the exception that if ed does not find a pattern it's an error, while sed just continues with the next line. For instance, let's say that you want to change foo to bar on the first line of the file and add something after the next line, ed will stop if it cannot find foo on the first line, sed will continue.</p> <pre><code>#Gnu sed version\nsed -e '1s/foo/bar/' -e '$a\\something' file\n\n#First ed version, does nothing if foo is not found on the first line:\ned -s file &lt;&lt;&lt; $'H\\n1s/foo/bar/\\na\\nsomething\\n.\\nw'\n</code></pre> <p>If you want the same behaviour you can use g/foo/ to trick ed. g/foo/ will apply the command on all lines matching foo, thus the substitution will succeed and ed will not produce an error when foo is not found:</p> <pre><code>#Second version will add the line with \"something\" even if foo is not found\ned -s file &lt;&lt;&lt; $'H\\n1g/foo/s/foo/bar/\\na\\nsomething\\n.\\nw'\n</code></pre> <p>In fact, even a substitution that fails after a g/ / command does not seem to cause an error, i.e. you can use a trick like g/./s/foo/bar/ to attempt the substitution on all non blank lines</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#here-documents","title":"here documents","text":"<p>__ shell parameters are expanded __</p> <p>If you don't quote the delimiter, <code>$</code> has a special meaning. This sounds obvious but it's easy to forget this fact when you use addresses like <code>$-1</code> or commands like <code>$a</code>. Either quote the <code>$</code> or the delimiter:</p> <pre><code>#fails\ned -s file &lt;&lt; EOF\n$a\nlast line\n.\nw\nEOF\n\n#ok\ned -s file &lt;&lt; EOF\n$a\nlast line\n.\nw\nEOF\n\n#ok again\ned -s file &lt;&lt; 'EOF'\n$a\nlast line\n.\nw\nEOF\n</code></pre> <p>__ \".\" is not a command __</p> <p>The . used to terminate the command \"a\" must be the only thing on the line. take care if you indent the commands:</p> <pre><code>#ed doesn't care about the spaces before the commands, but the . must be the only thing on the line:\ned -s file &lt;&lt; EOF\n a\nmy content\n.\n w\nEOF\n</code></pre>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#simulate-other-commands","title":"Simulate other commands","text":"<p>Keep in mind that in all the examples below, the entire file will be read into memory.</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#a-simple-grep","title":"A simple grep","text":"<pre><code>ed -s file &lt;&lt;&lt; 'g/foo/p'\n\n# equivalent\ned -s file &lt;&lt;&lt; 'g/foo/'\n</code></pre> <p>The name <code>grep</code> is derived from the notaion <code>g/RE/p</code> (global =&gt; regular expression =&gt; print). ref http://www.catb.org/~esr/jargon/html/G/grep.html</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#wc-l","title":"wc -l","text":"<p>Since the default for the <code>ed</code> \"print line number\" command is the last line, a simple <code>=</code> (equal sign) will print this line number and thus the number of lines of the file:</p> <pre><code>ed -s file &lt;&lt;&lt; '='\n</code></pre>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#cat","title":"cat","text":"<p>Yea, it's a joke...</p> <pre><code>ed -s file &lt;&lt;&lt; $',p'\n</code></pre> <p>...but a similar thing to <code>cat</code> showing line-endings and escapes can be done with the <code>list</code> command (l):</p> <pre><code>ed -s file &lt;&lt;&lt; $',l'\n</code></pre> <p>FIXME</p> <p>to be continued</p>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/edit-ed/#links","title":"Links","text":"<p>Reference:</p> <ul> <li>Gnu ed - if we had to guess, you're probably using this one.</li> <li>POSIX ed, ex, and vi</li> <li>http://sdf.lonestar.org/index.cgi?tutorials/ed - ed cheatsheet on sdf.org</li> </ul> <p>Misc info / tutorials:</p> <ul> <li>How can I replace a string with another string in a variable, a stream, a file, or in all the files in a directory? - BashFAQ</li> <li>http://wolfram.schneider.org/bsd/7thEdManVol2/edtut/edtut.pdf - Old but still relevant ed tutorial.</li> </ul>","tags":["bash","shell","scripting","arguments","file","editor","edit","ed","sed"]},{"location":"howto/getopts_tutorial/","title":"Small getopts tutorial","text":"","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#description","title":"Description","text":"<p>Note that <code>getopts</code> is neither able to parse GNU-style long options (<code>--myoption</code>) nor XF86-style long options (<code>-myoption</code>). So, when you want to parse command line arguments in a professional ;-) way, <code>getopts</code> may or may not work for you. Unlike its older brother <code>getopt</code> (note the missing s!), it's a shell builtin command. The advantages are:</p> <ul> <li>No need to pass the positional parameters through to an external program.</li> <li>Being a builtin, <code>getopts</code> can set shell variables to use for parsing (impossible for an external process!)</li> <li>There's no need to argue with several <code>getopt</code> implementations which had buggy concepts in the past (whitespace, ...)</li> <li><code>getopts</code> is defined in POSIX\u00ae.</li> </ul> <p>Some other methods to parse positional parameters - using neither getopt nor getopts - are described in: How to handle positional parameters.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#terminology","title":"Terminology","text":"<p>It's useful to know what we're talking about here, so let's see... Consider the following command line:</p> <pre><code>mybackup -x -f /etc/mybackup.conf -r ./foo.txt ./bar.txt\n</code></pre> <p>These are all positional parameters, but they can be divided into several logical groups:</p> <ul> <li><code>-x</code> is an option (aka flag or switch). It consists of a dash (<code>-</code>) followed by one character.</li> <li><code>-f</code> is also an option, but this option has an associated option argument (an argument to the option <code>-f</code>): <code>/etc/mybackup.conf</code>. The option argument is usually the argument following the option itself, but that isn't mandatory. Joining the option and option argument into a single argument <code>-f/etc/mybackup.conf</code> is valid.</li> <li><code>-r</code> depends on the configuration. In this example, <code>-r</code> doesn't take arguments so it's a standalone option like <code>-x</code>.</li> <li><code>./foo.txt</code> and <code>./bar.txt</code> are remaining arguments without any associated options. These are often used as mass-arguments. For example, the filenames specified for <code>cp(1)</code>, or arguments that don't need an option to be recognized because of the intended behavior of the program. POSIX\u00ae calls them operands.</li> </ul> <p>To give you an idea about why <code>getopts</code> is useful, The above command line is equivalent to:</p> <pre><code>mybackup -xrf /etc/mybackup.conf ./foo.txt ./bar.txt\n</code></pre> <p>which is complex to parse without the help of <code>getopts</code>.</p> <p>The option flags can be upper- and lowercase characters, or digits. It may recognize other characters, but that's not recommended (usability and maybe problems with special characters).</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#how-it-works","title":"How it works","text":"<p>In general you need to call <code>getopts</code> several times. Each time it will use the next positional parameter and a possible argument, if parsable, and provide it to you. <code>getopts</code> will not change the set of positional parameters. If you want to shift them, it must be done manually:</p> <pre><code>shift $((OPTIND-1))\n# now do something with $@\n</code></pre> <p>Since <code>getopts</code> sets an exit status of FALSE when there's nothing left to parse, it's easy to use in a while-loop:</p> <pre><code>while getopts ...; do\n ...\ndone\n</code></pre> <p><code>getopts</code> will parse options and their possible arguments. It will stop parsing on the first non-option argument (a string that doesn't begin with a hyphen (<code>-</code>) that isn't an argument for any option in front of it). It will also stop parsing when it sees the <code>--</code> (double-hyphen), which means end of options.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#used-variables","title":"Used variables","text":"variable description OPTIND Holds the index to the next argument to be processed. This is how <code>getopts</code> \"remembers\" its own status between invocations. Also useful to shift the positional parameters after processing with <code>getopts</code>. <code>OPTIND</code> is initially set to 1, and needs to be re-set to 1 if you want to parse anything again with getopts OPTARG This variable is set to any argument for an option found by <code>getopts</code>. It also contains the option flag of an unknown option. OPTERR (Values 0 or 1) Indicates if Bash should display error messages generated by the <code>getopts</code> builtin. The value is initialized to 1 on every shell startup - so be sure to always set it to 0 if you don't want to see annoying messages! <code>OPTERR</code> is not specified by POSIX for the <code>getopts</code> builtin utility --- only for the C <code>getopt()</code> function in <code>unistd.h</code> (<code>opterr</code>). <code>OPTERR</code> is bash-specific and not supported by shells such as ksh93, mksh, zsh, or dash. <p><code>getopts</code> also uses these variables for error reporting (they're set to value-combinations which arent possible in normal operation).</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#specify-what-you-want","title":"Specify what you want","text":"<p>The base-syntax for <code>getopts</code> is:</p> <pre><code>getopts OPTSTRING VARNAME [ARGS...]\n</code></pre> <p>where:</p> Option Description <code>OPTSTRING</code> tells <code>getopts</code> which options to expect and where to expect arguments (see below) <code>VARNAME</code> tells <code>getopts</code> which shell-variable to use for option reporting <code>ARGS</code> tells <code>getopts</code> to parse these optional words instead of the positional parameters","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#the-option-string","title":"The option-string","text":"<p>The option-string tells <code>getopts</code> which options to expect and which of them must have an argument. The syntax is very simple --- every option character is simply named as is, this example-string would tell <code>getopts</code> to look for <code>-f</code>, <code>-A</code> and <code>-x</code>:</p> <pre><code>getopts fAx VARNAME\n</code></pre> <p>When you want <code>getopts</code> to expect an argument for an option, just place a <code>:</code> (colon) after the proper option flag. If you want <code>-A</code> to expect an argument (i.e. to become <code>-A SOMETHING</code>) just do:</p> <pre><code>getopts fA:x VARNAME\n</code></pre> <p>If the very first character of the option-string is a <code>:</code> (colon), which would normally be nonsense because there's no option letter preceding it, <code>getopts</code> switches to \"silent error reporting mode\". In productive scripts, this is usually what you want because it allows you to handle errors yourself without being disturbed by annoying messages.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#custom-arguments-to-parse","title":"Custom arguments to parse","text":"<p>The <code>getopts</code> utility parses the positional parameters of the current shell or function by default (which means it parses <code>\"$@\"</code>).</p> <p>You can give your own set of arguments to the utility to parse. Whenever additional arguments are given after the <code>VARNAME</code> parameter, <code>getopts</code> doesn't try to parse the positional parameters, but these given words.</p> <p>This way, you are able to parse any option set you like, here for example from an array:</p> <pre><code>while getopts :f:h opt \"${MY_OWN_SET[@]}\"; do\n ...\ndone\n</code></pre> <p>A call to <code>getopts</code> without these additional arguments is equivalent to explicitly calling it with <code>\"$@\"</code>:</p> <pre><code>getopts ... \"$@\"\n</code></pre>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#error-reporting","title":"Error Reporting","text":"<p>Regarding error-reporting, there are two modes <code>getopts</code> can run in:</p> <ul> <li>verbose mode</li> <li>silent mode</li> </ul> <p>For productive scripts I recommend to use the silent mode, since everything looks more professional, when you don't see annoying standard messages. Also it's easier to handle, since the failure cases are indicated in an easier way.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#verbose-mode","title":"Verbose Mode","text":"failure message invalid option <code>VARNAME</code> is set to <code>?</code> (question-mark) and <code>OPTARG</code> is unset required argument not found <code>VARNAME</code> is set to <code>?</code> (question-mark), <code>OPTARG</code> is unset and an error message is printed","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#silent-mode","title":"Silent Mode","text":"failure message invalid option <code>VARNAME</code> is set to <code>?</code> (question-mark) and <code>OPTARG</code> is set to the (invalid) option character required argument not found <code>VARNAME</code> is set to <code>:</code> (colon) and <code>OPTARG</code> contains the option-character in question","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#using-it","title":"Using it","text":"","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#a-first-example","title":"A first example","text":"<p>Enough said - action!</p> <p>Let's play with a very simple case: only one option (<code>-a</code>) expected, without any arguments. Also we disable the verbose error handling by preceding the whole option string with a colon (<code>:</code>):</p> <pre><code>#!/bin/bash\n\nwhile getopts \":a\" opt; do\n case $opt in\n a)\n echo \"-a was triggered!\" &gt;&amp;2\n ;;\n \\?)\n echo \"Invalid option: -$OPTARG\" &gt;&amp;2\n ;;\n esac\ndone\n</code></pre> <p>I put that into a file named <code>go_test.sh</code>, which is the name you'll see below in the examples.</p> <p>Let's do some tests:</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#calling-it-without-any-arguments","title":"Calling it without any arguments","text":"<pre><code>$ ./go_test.sh\n$\n</code></pre> <p>Nothing happened? Right. <code>getopts</code> didn't see any valid or invalid options (letters preceded by a dash), so it wasn't triggered.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#calling-it-with-non-option-arguments","title":"Calling it with non-option arguments","text":"<pre><code>$ ./go_test.sh /etc/passwd\n$\n</code></pre> <p>Again --- nothing happened. The very same case: <code>getopts</code> didn't see any valid or invalid options (letters preceded by a dash), so it wasn't triggered.</p> <p>The arguments given to your script are of course accessible as <code>$1</code> - <code>${N}</code>.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#calling-it-with-option-arguments","title":"Calling it with option-arguments","text":"<p>Now let's trigger <code>getopts</code>: Provide options.</p> <p>First, an invalid one:</p> <pre><code>$ ./go_test.sh -b\nInvalid option: -b\n$\n</code></pre> <p>As expected, <code>getopts</code> didn't accept this option and acted like told above: It placed <code>?</code> into <code>$opt</code> and the invalid option character (<code>b</code>) into <code>$OPTARG</code>. With our <code>case</code> statement, we were able to detect this.</p> <p>Now, a valid one (<code>-a</code>):</p> <pre><code>$ ./go_test.sh -a\n-a was triggered!\n$\n</code></pre> <p>You see, the detection works perfectly. The <code>a</code> was put into the variable <code>$opt</code> for our case statement.</p> <p>Of course it's possible to mix valid and invalid options when calling:</p> <pre><code>$ ./go_test.sh -a -x -b -c\n-a was triggered!\nInvalid option: -x\nInvalid option: -b\nInvalid option: -c\n$\n</code></pre> <p>Finally, it's of course possible, to give our option multiple times:</p> <pre><code>$ ./go_test.sh -a -a -a -a\n-a was triggered!\n-a was triggered!\n-a was triggered!\n-a was triggered!\n$\n</code></pre> <p>The last examples lead us to some points you may consider:</p> <ul> <li>invalid options don't stop the processing: If you want to stop the script, you have to do it yourself (<code>exit</code> in the right place)</li> <li>multiple identical options are possible: If you want to disallow these, you have to check manually (e.g. by setting a variable or so)</li> </ul>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#an-option-with-argument","title":"An option with argument","text":"<p>Let's extend our example from above. Just a little bit:</p> <ul> <li><code>-a</code> now takes an argument</li> <li>on an error, the parsing exits with <code>exit 1</code></li> </ul> <pre><code>#!/bin/bash\n\nwhile getopts \":a:\" opt; do\n case $opt in\n a)\n echo \"-a was triggered, Parameter: $OPTARG\" &gt;&amp;2\n ;;\n \\?)\n echo \"Invalid option: -$OPTARG\" &gt;&amp;2\n exit 1\n ;;\n :)\n echo \"Option -$OPTARG requires an argument.\" &gt;&amp;2\n exit 1\n ;;\n esac\ndone\n</code></pre> <p>Let's do the very same tests we did in the last example:</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#calling-it-without-any-arguments_1","title":"Calling it without any arguments","text":"<pre><code>$ ./go_test.sh\n$\n</code></pre> <p>As above, nothing happened. It wasn't triggered.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#calling-it-with-non-option-arguments_1","title":"Calling it with non-option arguments","text":"<pre><code>$ ./go_test.sh /etc/passwd\n$\n</code></pre> <p>The very same case: It wasn't triggered.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#calling-it-with-option-arguments_1","title":"Calling it with option-arguments","text":"<p>Invalid option:</p> <pre><code>$ ./go_test.sh -b\nInvalid option: -b\n$\n</code></pre> <p>As expected, as above, <code>getopts</code> didn't accept this option and acted like programmed.</p> <p>Valid option, but without the mandatory argument:</p> <pre><code>$ ./go_test.sh -a\nOption -a requires an argument.\n$\n</code></pre> <p>The option was okay, but there is an argument missing.</p> <p>Let's provide the argument:</p> <pre><code>$ ./go_test.sh -a /etc/passwd\n-a was triggered, Parameter: /etc/passwd\n$\n</code></pre>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/getopts_tutorial/#see-also","title":"See also","text":"<ul> <li>Internal: posparams</li> <li>Internal: case</li> <li>Internal: while_loop</li> <li>POSIX getopts(1) and getopt(3)</li> <li>parse CLI ARGV</li> <li>handle command-line arguments (options) to a script</li> </ul>","tags":["bash","shell","scripting","arguments","positional","parameters","options","getopt","getopts"]},{"location":"howto/mutex/","title":"Lock your script (against parallel execution)","text":"","tags":["bash","shell","scripting","mutex","locking","run-control"]},{"location":"howto/mutex/#why-lock","title":"Why lock?","text":"<p>Sometimes there's a need to ensure only one copy of a script runs, i.e prevent two or more copies running simultaneously. Imagine an important cronjob doing something very important, which will fail or corrupt data if two copies of the called program were to run at the same time. To prevent this, a form of <code>MUTEX</code> (mutual exclusion) lock is needed.</p> <p>The basic procedure is simple: The script checks if a specific condition (locking) is present at startup, if yes, it's locked - the scipt doesn't start.</p> <p>This article describes locking with common UNIX\u00ae tools. There are other special locking tools available, But they're not standardized, or worse yet, you can't be sure they're present when you want to run your scripts. A tool designed for specifically for this purpose does the job much better than general purpose code.</p>","tags":["bash","shell","scripting","mutex","locking","run-control"]},{"location":"howto/mutex/#other-special-locking-tools","title":"Other, special locking tools","text":"<p>As told above, a special tool for locking is the preferred solution. Race conditions are avoided, as is the need to work around specific limits.</p> <ul> <li><code>flock</code>: http://www.kernel.org/pub/software/utils/script/flock/</li> <li><code>solo</code>: http://timkay.com/solo/</li> </ul>","tags":["bash","shell","scripting","mutex","locking","run-control"]},{"location":"howto/mutex/#choose-the-locking-method","title":"Choose the locking method","text":"<p>The best way to set a global lock condition is the UNIX\u00ae filesystem. Variables aren't enough, as each process has its own private variable space, but the filesystem is global to all processes (yes, I know about chroots, namespaces, ... special case). You can \"set\" several things in the filesystem that can be used as locking indicator:</p> <ul> <li>create files</li> <li>update file timestamps</li> <li>create directories</li> </ul> <p>To create a file or set a file timestamp, usually the command touch is used. The following problem is implied: A locking mechanism checks for the existance of the lockfile, if no lockfile exists, it creates one and continues. Those are two separate steps! That means it's not an atomic operation. There's a small amount of time between checking and creating, where another instance of the same script could perform locking (because when it checked, the lockfile wasn't there)! In that case you would have 2 instances of the script running, both thinking they are succesfully locked, and can operate without colliding. Setting the timestamp is similar: One step to check the timespamp, a second step to set the timestamp.</p> <p>Conclusion: We need an operation that does the check and the locking in one step.</p> <p>A simple way to get that is to create a lock directory - with the mkdir command. It will:</p> <pre><code> * create a given directory only if it does not exist, and set a successful exit code\n * it will set an unsuccesful exit code if an error occours - for example, if the directory specified already exists\n</code></pre> <p>With mkdir it seems, we have our two steps in one simple operation. A (very!) simple locking code might look like this:</p> <pre><code>if mkdir /var/lock/mylock; then\n echo \"Locking succeeded\" &gt;&amp;2\nelse\n echo \"Lock failed - exit\" &gt;&amp;2\n exit 1\nfi\n</code></pre> <p>In case <code>mkdir</code> reports an error, the script will exit at this point - the MUTEX did its job!</p> <p>If the directory is removed after setting a successful lock, while the script is still running, the lock is lost. Doing chmod -w for the parent directory containing the lock directory can be done, but it is not atomic. Maybe a while loop checking continously for the existence of the lock in the background and sending a signal such as USR1, if the directory is not found, can be done. The signal would need to be trapped. I am sure there there is a better solution than this suggestion --- sn18 2009/12/19 08:24*</p> <p>Note: While perusing the Internet, I found some people asking if the <code>mkdir</code> method works \"on all filesystems\". Well, let's say it should. The syscall under <code>mkdir</code> is guarenteed to work atomicly in all cases, at least on Unices. Two examples of problems are NFS filesystems and filesystems on cluster servers. With those two scenarios, dependencies exist related to the mount options and implementation. However, I successfully use this simple method on an Oracle OCFS2 filesystem in a 4-node cluster environment. So let's just say \"it should work under normal conditions\".</p> <p>Another atomic method is setting the <code>noclobber</code> shell option (<code>set -C</code>). That will cause redirection to fail, if the file the redirection points to already exists (using diverse <code>open()</code> methods). Need to write a code example here.</p> <pre><code>if ( set -o noclobber; echo \"locked\" &gt; \"$lockfile\") 2&gt; /dev/null; then\n trap 'rm -f \"$lockfile\"; exit $?' INT TERM EXIT\n echo \"Locking succeeded\" &gt;&amp;2\n rm -f \"$lockfile\"\nelse\n echo \"Lock failed - exit\" &gt;&amp;2\n exit 1\nfi\n</code></pre> <p>Another explanation of this basic pattern using <code>set -C</code> can be found here.</p>","tags":["bash","shell","scripting","mutex","locking","run-control"]},{"location":"howto/mutex/#an-example","title":"An example","text":"<p>This code was taken from a production grade script that controls PISG to create statistical pages from my IRC logfiles. There are some differences compared to the very simple example above:</p> <ul> <li>the locking stores the process ID of the locked instance</li> <li>if a lock fails, the script tries to find out if the locked instance still is active (unreliable!)</li> <li>traps are created to automatically remove the lock when the script terminates, or is killed</li> </ul> <p>Details on how the script is killed aren't given, only code relevant to the locking process is shown:</p> <pre><code>#!/bin/bash\n\n# lock dirs/files\nLOCKDIR=\"/tmp/statsgen-lock\"\nPIDFILE=\"${LOCKDIR}/PID\"\n\n# exit codes and text\nENO_SUCCESS=0; ETXT[0]=\"ENO_SUCCESS\"\nENO_GENERAL=1; ETXT[1]=\"ENO_GENERAL\"\nENO_LOCKFAIL=2; ETXT[2]=\"ENO_LOCKFAIL\"\nENO_RECVSIG=3; ETXT[3]=\"ENO_RECVSIG\"\n\n###\n### start locking attempt\n###\n\ntrap 'ECODE=$?; echo \"[statsgen] Exit: ${ETXT[ECODE]}($ECODE)\" &gt;&amp;2' 0\necho -n \"[statsgen] Locking: \" &gt;&amp;2\n\nif mkdir \"${LOCKDIR}\" &amp;&gt;/dev/null; then\n\n # lock succeeded, install signal handlers before storing the PID just in case\n # storing the PID fails\n trap 'ECODE=$?;\n echo \"[statsgen] Removing lock. Exit: ${ETXT[ECODE]}($ECODE)\" &gt;&amp;2\n rm -rf \"${LOCKDIR}\"' 0\n echo \"$$\" &gt;\"${PIDFILE}\"\n # the following handler will exit the script upon receiving these signals\n # the trap on \"0\" (EXIT) from above will be triggered by this trap's \"exit\" command!\n trap 'echo \"[statsgen] Killed by a signal.\" &gt;&amp;2\n exit ${ENO_RECVSIG}' 1 2 3 15\n echo \"success, installed signal handlers\"\n\nelse\n\n # lock failed, check if the other PID is alive\n OTHERPID=\"$(cat \"${PIDFILE}\")\"\n\n # if cat isn't able to read the file, another instance is probably\n # about to remove the lock -- exit, we're *still* locked\n # Thanks to Grzegorz Wierzowiecki for pointing out this race condition on\n # http://wiki.grzegorz.wierzowiecki.pl/code:mutex-in-bash\n if [ $? != 0 ]; then\n echo \"lock failed, PID ${OTHERPID} is active\" &gt;&amp;2\n exit ${ENO_LOCKFAIL}\n fi\n\n if ! kill -0 $OTHERPID &amp;&gt;/dev/null; then\n # lock is stale, remove it and restart\n echo \"removing stale lock of nonexistant PID ${OTHERPID}\" &gt;&amp;2\n rm -rf \"${LOCKDIR}\"\n echo \"[statsgen] restarting myself\" &gt;&amp;2\n exec \"$0\" \"$@\"\n else\n # lock is valid and OTHERPID is active - exit, we're locked!\n echo \"lock failed, PID ${OTHERPID} is active\" &gt;&amp;2\n exit ${ENO_LOCKFAIL}\n fi\n\nfi\n</code></pre>","tags":["bash","shell","scripting","mutex","locking","run-control"]},{"location":"howto/mutex/#related-links","title":"Related links","text":"<ul> <li>BashFAQ/045</li> <li>Implementation of a shell locking utility</li> <li>Wikipedia article on File Locking, including a discussion of potential problems with flock and certain versions of NFS.</li> </ul>","tags":["bash","shell","scripting","mutex","locking","run-control"]},{"location":"howto/pax/","title":"pax - the POSIX archiver","text":"<p>pax can do a lot of fancy stuff, feel free to contribute more awesome pax tricks!</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#introduction","title":"Introduction","text":"<p>The POSIX archiver, <code>pax</code>, is an attempt at a standardized archiver with the best features of <code>tar</code> and <code>cpio</code>, able to handle all common archive types.</p> <p>However, this is not a manpage, it will not list all possible options, it will not you detailed information about <code>pax</code>. It's only an introduction.</p> <p>This article is based on the debianized Berkeley implementation of <code>pax</code>, but implementation-specific things should be tagged as such. Unfortunately, the Debian package doesn't seem to be maintained anymore.</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#overview","title":"Overview","text":"","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#operation-modes","title":"Operation modes","text":"<p>There are four basic operation modes to list, read, write and copy archives. They're switched with combinations of <code>-r</code> and <code>-w</code> command line options:</p> Mode RW-Options List no RW-options Read <code>-r</code> Write <code>-w</code> Copy <code>-r -w</code>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#list","title":"List","text":"<p>In list mode, <code>pax</code> writes the list of archive members to standard output (a table of contents). If a pattern match is specified on the command line, only matching filenames are printed.</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#read","title":"Read","text":"<p>Read an archive. <code>pax</code> will read archive data and extract the members to the current directory. If a pattern match is specified on the command line, only matching filenames are extracted.</p> <p>When reading an archive, the archive type is determined from the archive data.</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#write","title":"Write","text":"<p>Write an archive, which means create a new one or append to an existing one. All files and directories specified on the command line are inserted into the archive. The archive is written to standard output by default.</p> <p>If no files are specified on the command line, filenames are read from <code>STDIN</code>.</p> <p>The write mode is the only mode where you need to specify the archive type with <code>-x &lt;TYPE&gt;</code>, e.g. <code>-x ustar</code>.</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#copy","title":"Copy","text":"<p>Copy mode is similar to <code>cpio</code> passthrough mode. It provides a way to replicate a complete or partial file hierarchy (with all the <code>pax</code> options, e.g. rewriting groups) to another location.</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#archive-data","title":"Archive data","text":"<p>When you don't specify anything special, <code>pax</code> will attempt to read archive data from standard input (read/list modes) and write archive data to standard output (write mode). This ensures <code>pax</code> can be easily used as part of a shell pipe construct, e.g. to read a compressed archive that's decompressed in the pipe.</p> <p>The option to specify the pathname of a file to be archived is <code>-f</code> This file will be used as input or output, depending on the operation (read/write/list).</p> <p>When pax reads an archive, it tries to guess the archive type. However, in write mode, you must specify which type of archive to append using the <code>-x &lt;TYPE&gt;</code> switch. If you omit this switch, a default archive will be created (POSIX says it's implementation defined, Berkeley <code>pax</code> creates <code>ustar</code> if no options are specified).</p> <p>The following archive formats are supported (Berkeley implementation):</p> ustar POSIX TAR format (default) cpio POSIX CPIO format tar classic BSD TAR format bcpio old binary CPIO format sv4cpio SVR4 CPIO format sv4crc SVR4 CPIO format with CRC <p>Berkeley <code>pax</code> supports options <code>-z</code> and <code>-j</code>, similar to GNU <code>tar</code>, to filter archive files through GZIP/BZIP2.</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#matching-archive-members","title":"Matching archive members","text":"<p>In read and list modes, you can specify patterns to determine which files to list or extract.</p> <ul> <li>the pattern notation is the one known by a POSIX-shell, i.e. the one known by Bash without <code>extglob</code></li> <li>if the specified pattern matches a complete directory, it affects all files and subdirectories of the specified directory</li> <li>if you specify the <code>-c</code> option, <code>pax</code> will invert the matches, i.e. it matches all filenames except those matching the specified patterns</li> <li>if no patterns are given, <code>pax</code> will \"match\" (list or extract) all files from the archive</li> <li>To avoid conflicts with shell pathname expansion, it's wise to quote patterns!</li> </ul>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#some-assorted-examples-of-patterns","title":"Some assorted examples of patterns","text":"<pre><code>pax -r &lt;myarchive.tar 'data/sales/*.txt' 'data/products/*.png'\n\npax -r &lt;myarchive.tar 'data/sales/year_200[135].txt'\n# should be equivalent to\npax -r &lt;myarchive.tar 'data/sales/year_2001.txt' 'data/sales/year_2003.txt' 'data/sales/year_2005.txt'\n</code></pre>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#using-pax","title":"Using pax","text":"<p>This is a brief description of using <code>pax</code> as a normal archiver system, like you would use <code>tar</code>.</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#creating-an-archive","title":"Creating an archive","text":"<p>This task is done with basic syntax</p> <pre><code># archive contents to stdout\npax -w &gt;archive.tar README.txt *.png data/\n\n# equivalent, extract archive contents directly to a file\npax -w -x ustar -f archive.tar README.txt *.png data/\n</code></pre> <p><code>pax</code> is in write mode, the given filenames are packed into an archive:</p> <ul> <li><code>README.txt</code> is a normal file, it will be packed</li> <li><code>*.png</code> is a pathname glob for your shell, the shell will substitute all matching filenames before <code>pax</code> is executed. The result is a list of filenames that will be packed like the <code>README.txt</code> example above</li> <li><code>data/</code> is a directory. Everything in this directory will be packed into the archive, i.e. not just an empty directory</li> </ul> <p>When you specify the <code>-v</code> option, <code>pax</code> will write the pathnames of the files inserted into the archive to <code>STDERR</code>.</p> <p>When, and only when, no filename arguments are specified, <code>pax</code> attempts to read filenames from <code>STDIN</code>, separated by newlines. This way you can easily combine <code>find</code> with <code>pax</code>:</p> <pre><code>find . -name '*.txt' | pax -wf textfiles.tar -x ustar\n</code></pre>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#listing-archive-contents","title":"Listing archive contents","text":"<p>The standard output format to list archive members simply is to print each filename to a separate line. But the output format can be customized to include permissions, timestamps, etc. with the <code>-o listopt=&lt;FORMAT&gt;</code> specification. The syntax of the format specification is strongly derived from the <code>printf(3)</code> format specification.</p> <p>Unfortunately the <code>pax</code> utility delivered with Debian doesn't seem to support these extended listing formats.</p> <p>However, <code>pax</code> lists archive members in a <code>ls -l</code>-like format, when you give the <code>-v</code> option:</p> <pre><code>pax -v &lt;myarchive.tar\n# or, of course\npax -vf myarchive.tar\n</code></pre>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#extracting-from-an-archive","title":"Extracting from an archive","text":"<p>You can extract all files, or files (not) matching specific patterns from an archive using constructs like:</p> <pre><code># \"normal\" extraction\npax -rf myarchive.tar '*.txt'\n\n# with inverted pattern\npax -rf myarchive.tar -c '*.txt'\n</code></pre>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#copying-files","title":"Copying files","text":"<p>To copy directory contents to another directory, similar to a <code>cp -a</code> command, use:</p> <pre><code>mkdir destdir\npax -rw dir destdir #creates a copy of dir in destdir/, i.e. destdir/dir\n</code></pre>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#copying-files-via-ssh","title":"Copying files via ssh","text":"<p>To copy directory contents to another directory on a remote system, use:</p> <pre><code>pax -w localdir | ssh user@host \"cd distantdest &amp;&amp; pax -r -v\"\npax -w localdir | gzip | ssh user@host \"cd distantdir &amp;&amp; gunzip | pax -r -v\" #compress the sent data\n</code></pre> <p>These commands create a copy of localdir in distandir (distantdir/dir) on the remote machine.</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#advanced-usage","title":"Advanced usage","text":"","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#backup-your-daily-work","title":"Backup your daily work","text":"<p>Note: <code>-T</code> is an extension and is not defined by POSIX.</p> <p>Say you have write-access to a fileserver mounted on your filesystem tree. In copy mode, you can tell <code>pax</code> to copy only files that were modified today:</p> <pre><code>mkdir /n/mybackups/$(date +%A)/\npax -rw -T 0000 data/ /n/mybackups/$(date +%A)/\n</code></pre> <p>This is done using the <code>-T</code> switch, which normally allows you to specify a time window, but in this case, only the start time which means \"today at midnight\".</p> <p>When you execute this \"very simple backup\" after your daily work, you will have a copy of the modified files.</p> <p>Note: The <code>%A</code> format from <code>date</code> expands to the name of the current day, localized, e.g. \"Friday\" (en) or \"Mittwoch\" (de).</p> <p>The same, but with an archive, can be accomplished by:</p> <pre><code>pax -w -T 0000 -f /n/mybackups/$(date +%A)\n</code></pre> <p>In this case, the day-name is an archive-file (you don't need a filename extension like <code>.tar</code> but you can add one, if desired).</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#changing-filenames-while-archiving","title":"Changing filenames while archiving","text":"<p><code>pax</code> is able to rewrite filenames while archiving or while extracting from an archive. This example creates a tar archive containing the <code>holiday_2007/</code> directory, but the directory name inside the archive will be <code>holiday_pics/</code>:</p> <pre><code>pax -x ustar -w -f holiday_pictures.tar -s '/^holiday_2007/holiday_pics/' holiday_2007/\n</code></pre> <p>The option responsible for the string manipulation is the <code>-s &lt;REWRITE-SPECIFICATION&gt;</code>. It takes the string rewrite specification as an argument, in the form <code>/OLD/NEW/[gp]</code>, which is an <code>ed(1)</code>-like regular expression (BRE) for <code>old</code> and generally can be used like the popular sed construct <code>s/from/to/</code>. Any non-null character can be used as a delimiter, so to mangle pathnames (containing slashes), you could use <code>#/old/path#/new/path#</code>.</p> <p>The optional <code>g</code> and <code>p</code> flags are used to apply substitution (g)lobally to the line or to (p)rint the original and rewritten strings to <code>STDERR</code>.</p> <p>Multiple <code>-s</code> options can be specified on the command line. They are applied to the pathname strings of the files or archive members. This happens in the order they are specified.</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#excluding-files-from-an-archive","title":"Excluding files from an archive","text":"<p>The -s command seen above can be used to exclude a file. The substitution must result in a null string: For example, let's say that you want to exclude all the CVS directories to create a source code archive. We are going to replace the names containing /CVS/ with nothing, note the <code>.*</code> they are needed because we need to match the entire pathname.</p> <pre><code> pax -w -x ustar -f release.tar -s',.*/CVS/.*,,' myapplication\n</code></pre> <p>You can use several -s options, for instance, let's say you also want to remove files ending in <code>~</code>:</p> <pre><code> pax -w -x ustar -f release.tar -'s,.*/CVS/.*,,' -'s/.*~//' myapplication\n</code></pre> <p>This can also be done while reading an archive, for instance, suppose you have an archive containing a \"usr\" and a \"etc\" directory but that you want to extract only the \"usr\" directory:</p> <pre><code>pax -r -f archive.tar -s',^etc/.*,,' #the etc/ dir is not extracted\n</code></pre>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#getting-archive-filenames-from-stdin","title":"Getting archive filenames from STDIN","text":"<p>Like <code>cpio</code>, pax can read filenames from standard input (<code>stdin</code>). This provides great flexibility - for example, a <code>find(1)</code> command may select files/directories in ways pax can't do itself. In write mode (creating an archive) or copy mode, when no filenames are given, pax expects to read filenames from standard input. For example:</p> <pre><code># Back up config files changed less than 3 days ago\nfind /etc -type f -mtime -3 | pax -x ustar -w -f /backups/etc.tar\n\n# Copy only the directories, not the files\nmkdir /target\nfind . -type d -print | pax -r -w -d /target\n\n# Back up anything that changed since the last backup\nfind . -newer /var/run/mylastbackup -print0 |\n pax -0 -x ustar -w -d -f /backups/mybackup.tar\ntouch /var/run/mylastbackup\n</code></pre> <p>The <code>-d</code> option tells pax <code>not</code> to recurse into directories it reads (<code>cpio</code>-style). Without <code>-d</code>, pax recurses into all directories (<code>tar</code>-style).</p> <p>Note: the <code>-0</code> option is not standard, but is present in some implementations.</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#from-tar-to-pax","title":"From tar to pax","text":"<p><code>pax</code> can handle the <code>tar</code> archive format, if you want to switch to the standard tool an alias like:</p> <pre><code>alias tar='echo USE PAX, idiot. pax is the standard archiver!; # '\n</code></pre> <p>in your <code>~/.bashrc</code> can be useful :-D.</p> <p>Here is a quick table comparing (GNU) <code>tar</code> and <code>pax</code> to help you to make the switch:</p> TAR PAX Notes <code>tar xzvf file.tar.gz</code> <code>pax -rvz -f file.tar.gz</code> <code>-z</code> is an extension, POSIXly: <code>gunzip &lt;file.tar.gz | pax -rv</code> <code>tar czvf archive.tar.gz path ...</code> <code>pax -wvz -f archive.tar.gz path ...</code> <code>-z</code> is an extension, POSIXly: <code>pax -wv path | gzip &gt; archive.tar.gz</code> <code>tar xjvf file.tar.bz2</code> <code>bunzip2 &lt;file.tar.bz2 | pax -rv</code> <code>tar cjvf archive.tar.bz2 path ...</code> <code>pax -wv path | bzip2 &gt; archive.tar.bz2</code> <code>tar tzvf file.tar.gz</code> <code>pax -vz -f file.tar.gz</code> <code>-z</code> is an extension, POSIXly: <code>gunzip &lt;file.tar.gz | pax -v</code> <p><code>pax</code> might not create ustar (<code>tar</code>) archives by default but its own pax format, add <code>-x ustar</code> if you want to ensure pax creates tar archives!</p>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/pax/#implementations","title":"Implementations","text":"<ul> <li>AT&amp;T AST toolkit | manpage</li> <li>Heirloom toolchest | manpage</li> <li>OpenBSD pax | manpage</li> <li>MirBSD pax | manpage - Debian bases their package upon this.</li> <li>SUS pax specification</li> </ul>","tags":["bash","shell","scripting","POSIX","archive","tar","packing","zip"]},{"location":"howto/redirection_tutorial/","title":"Illustrated Redirection Tutorial","text":"<p>This tutorial is not a complete guide to redirection, it will not cover here docs, here strings, name pipes etc... I just hope it'll help you to understand what things like <code>3&gt;&amp;2</code>, <code>2&gt;&amp;1</code> or <code>1&gt;&amp;3-</code> do.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#stdin-stdout-stderr","title":"stdin, stdout, stderr","text":"<p>When Bash starts, normally, 3 file descriptors are opened, <code>0</code>, <code>1</code> and <code>2</code> also known as standard input (<code>stdin</code>), standard output (<code>stdout</code>) and standard error (<code>stderr</code>).</p> <p>For example, with Bash running in a Linux terminal emulator, you'll see:</p> <pre><code># lsof +f g -ap $BASHPID -d 0,1,2\nCOMMAND PID USER FD TYPE FILE-FLAG DEVICE SIZE/OFF NODE NAME\nbash 12135 root 0u CHR RW,LG 136,13 0t0 16 /dev/pts/5\nbash 12135 root 1u CHR RW,LG 136,13 0t0 16 /dev/pts/5\nbash 12135 root 2u CHR RW,LG 136,13 0t0 16 /dev/pts/5\n</code></pre> <p>This <code>/dev/pts/5</code> is a pseudo terminal used to emulate a real terminal. Bash reads (<code>stdin</code>) from this terminal and prints via <code>stdout</code> and <code>stderr</code> to this terminal.</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n</code></pre> <p>When a command, a compound command, a subshell etc. is executed, it inherits these file descriptors. For instance <code>echo foo</code> will send the text <code>foo</code> to the file descriptor <code>1</code> inherited from the shell, which is connected to <code>/dev/pts/5</code>.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#simple-redirections","title":"Simple Redirections","text":"","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#output-redirection-n-file","title":"Output Redirection \"n&gt; file\"","text":"<p><code>&gt;</code> is probably the simplest redirection.</p> <p><code>echo foo &gt; file</code></p> <p>the <code>&gt; file</code> after the command alters the file descriptors belonging to the command <code>echo</code>. It changes the file descriptor <code>1</code> (<code>&gt; file</code> is the same as <code>1&gt;file</code>) so that it points to the file <code>file</code>. They will look like:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| file |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n</code></pre> <p>Now characters written by our command, <code>echo</code>, that are sent to the standard output, i.e., the file descriptor <code>1</code>, end up in the file named <code>file</code>.</p> <p>In the same way, command <code>2&gt; file</code> will change the standard error and will make it point to <code>file</code>. Standard error is used by applications to print errors.</p> <p>What will <code>command 3&gt; file</code> do? It will open a new file descriptor pointing to <code>file</code>. The command will then start with:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nnew descriptor ( 3 ) ----&gt;| file |\n --- +-----------------------+\n</code></pre> <p>What will the command do with this descriptor? It depends. Often nothing. We will see later why we might want other file descriptors.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#input-redirection-n-file","title":"Input Redirection \"n&lt; file\"","text":"<p>When you run a commandusing <code>command &lt; file</code>, it changes the file descriptor <code>0</code> so that it looks like:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) &lt;----| file |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n</code></pre> <p>If the command reads from <code>stdin</code>, it now will read from <code>file</code> and not from the console.</p> <p>As with <code>&gt;</code>, <code>&lt;</code> can be used to open a new file descriptor for reading, <code>command 3&lt;file</code>. Later we will see how this can be useful.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#pipes","title":"Pipes |","text":"<p>What does this <code>|</code> do? Among other things, it connects the standard output of the command on the left to the standard input of the command on the right. That is, it creates a special file, a pipe, which is opened as a write destinaton for the left command, and as a read source for the right command.</p> <pre><code> echo foo | cat\n\n --- +--------------+ --- +--------------+\n( 0 ) ----&gt;| /dev/pts/5 | ------&gt; ( 0 ) ----&gt;|pipe (read) |\n --- +--------------+ / --- +--------------+\n /\n --- +--------------+ / --- +--------------+\n( 1 ) ----&gt;| pipe (write) | / ( 1 ) ----&gt;| /dev/pts |\n --- +--------------+ --- +--------------+\n\n --- +--------------+ --- +--------------+\n( 2 ) ----&gt;| /dev/pts/5 | ( 2 ) ----&gt;| /dev/pts/ |\n --- +--------------+ --- +--------------+\n</code></pre> <p>This is possible because the redirections are set up by the shell before the commands are executed, and the commands inherit the file descriptors.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#more-on-file-descriptors","title":"More On File Descriptors","text":"","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#duplicating-file-descriptor-21","title":"Duplicating File Descriptor 2&gt;&amp;1","text":"<p>We have seen how to open (or redirect) file descriptors. Let us see how to duplicate them, starting with the classic <code>2&gt;&amp;1</code>. What does this mean? That something written on the file descriptor <code>2</code> will go where file descriptor <code>1</code> goes. In a shell <code>command 2&gt;&amp;1</code> is not a very interesting example so we will use <code>ls /tmp/ doesnotexist 2&gt;&amp;1 | less</code></p> <pre><code> ls /tmp/ doesnotexist 2&gt;&amp;1 | less\n\n --- +--------------+ --- +--------------+\n( 0 ) ----&gt;| /dev/pts/5 | ------&gt; ( 0 ) ----&gt;|from the pipe |\n --- +--------------+ / ---&gt; --- +--------------+\n / /\n --- +--------------+ / / --- +--------------+\n( 1 ) ----&gt;| to the pipe | / / ( 1 ) ----&gt;| /dev/pts |\n --- +--------------+ / --- +--------------+\n /\n --- +--------------+ / --- +--------------+\n( 2 ) ----&gt;| to the pipe | / ( 2 ) ----&gt;| /dev/pts/ |\n --- +--------------+ --- +--------------+\n</code></pre> <p>Why is it called duplicating? Because after <code>2&gt;&amp;1</code>, we have 2 file descriptors pointing to the same file. Take care not to call this \"File Descriptor Aliasing\"; if we redirect <code>stdout</code> after <code>2&gt;&amp;1</code> to a file <code>B</code>, file descriptor <code>2</code> will still be opened on the file <code>A</code> where it was. This is often misunderstood by people wanting to redirect both standard input and standard output to the file. Continue reading for more on this.</p> <p>So if you have two file descriptors <code>s</code> and <code>t</code> like:</p> <pre><code> --- +-----------------------+\n a descriptor ( s ) ----&gt;| /some/file |\n --- +-----------------------+\n --- +-----------------------+\n a descriptor ( t ) ----&gt;| /another/file |\n --- +-----------------------+\n</code></pre> <p>Using a <code>t&gt;&amp;s</code> (where <code>t</code> and <code>s</code> are numbers) it means:</p> <p>Copy whatever file descriptor <code>s</code> contains into file descriptor <code>t</code></p> <p>So you got a copy of this descriptor:</p> <pre><code> --- +-----------------------+\n a descriptor ( s ) ----&gt;| /some/file |\n --- +-----------------------+\n --- +-----------------------+\n a descriptor ( t ) ----&gt;| /some/file |\n --- +-----------------------+\n</code></pre> <p>Internally each of these is represented by a file descriptor opened by the operating system's <code>fopen</code> calls, and is likely just a pointer to the file which has been opened for reading (<code>stdin</code> or file descriptor <code>0</code>) or writing (<code>stdout</code> /<code>stderr</code>).</p> <p>Note that the file reading or writing positions are also duplicated. If you have already read a line of <code>s</code>, then after <code>t&gt;&amp;s</code> if you read a line from <code>t</code>, you will get the second line of the file.</p> <p>Similarly for output file descriptors, writing a line to file descriptor <code>s</code> will append a line to a file as will writing a line to file descriptor <code>t</code>.</p> <p>Tip</p> <p>The syntax is somewhat confusing in that you would think that the arrow would point in the direction of the copy, but it's reversed. So it's <code>target&gt;&amp;source</code> effectively.</p> <p>So, as a simple example (albeit slightly contrived), is the following:</p> <pre><code>exec 3&gt;&amp;1 # Copy 1 into 3\nexec 1&gt; logfile # Make 1 opened to write to logfile\nlotsa_stdout # Outputs to fd 1, which writes to logfile\nexec 1&gt;&amp;3 # Copy 3 back into 1\necho Done # Output to original stdout\n</code></pre>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#order-of-redirection-ie-file-21-vs-21-file","title":"Order Of Redirection, i.e., \"<code>&gt; file 2&gt;&amp;1</code>\" vs. \"<code>2&gt;&amp;1 &gt;file</code>\"","text":"<p>While it doesn't matter where the redirections appears on the command line, their order does matter. They are set up from left to right.</p> <ul> <li><code>2&gt;&amp;1 &gt;file</code></li> </ul> <p>A common error, is to do <code>command 2&gt;&amp;1 &gt; file</code> to redirect both <code>stderr</code> and <code>stdout</code> to <code>file</code>. Let's see what's going on. First we type the command in our terminal, the descriptors look like this:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n</code></pre> <p>Then our shell, Bash sees <code>2&gt;&amp;1</code> so it duplicates 1, and the file descriptor look like this:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n</code></pre> <p>That's right, nothing has changed, 2 was already pointing to the same place as 1. Now Bash sees <code>&gt; file</code> and thus changes <code>stdout</code>:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| file |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n</code></pre> <p>And that's not what we want.</p> <ul> <li><code>&gt;file 2&gt;&amp;1</code></li> </ul> <p>Now let's look at the correct <code>command &gt;file 2&gt;&amp;1</code>. We start as in the previous example, and Bash sees <code>&gt; file</code>:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| file |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n</code></pre> <p>Then it sees our duplication <code>2&gt;&amp;1</code>:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| file |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| file |\n --- +-----------------------+\n</code></pre> <p>And voila, both <code>1</code> and <code>2</code> are redirected to file.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#why-sed-sfoobar-file-file-doesnt-work","title":"Why sed 's/foo/bar/' file &gt;file Doesn't Work","text":"<p>This is a common error, we want to modify a file using something that reads from a file and writes the result to <code>stdout</code>. To do this, we redirect stdout to the file we want to modify. The problem here is that, as we have seen, the redirections are setup before the command is actually executed.</p> <p>So BEFORE sed starts, standard output has already been redirected, with the additional side effect that, because we used &gt;, \"file\" gets truncated. When <code>sed</code> starts to read the file, it contains nothing.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#exec","title":"exec","text":"<p>In Bash the <code>exec</code> built-in replaces the shell with the specified program. So what does this have to do with redirection? <code>exec</code> also allow us to manipulate the file descriptors. If you don't specify a program, the redirection after <code>exec</code> modifies the file descriptors of the current shell.</p> <p>For example, all the commands after <code>exec 2&gt;file</code> will have file descriptors like:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| file |\n --- +-----------------------+\n</code></pre> <p>All the the errors sent to <code>stderr</code> by the commands after the <code>exec 2&gt;file</code> will go to the file, just as if you had the command in a script and ran <code>myscript 2&gt;file</code>.</p> <p><code>exec</code> can be used, if, for instance, you want to log the errors the commands in your script produce, just add <code>exec 2&gt;myscript.errors</code> at the beginning of your script.</p> <p>Let's see another use case. We want to read a file line by line, this is easy, we just do:</p> <pre><code> while read -r line;do echo \"$line\";done &lt; file\n</code></pre> <p>Now, we want, after printing each line, to do a pause, waiting for the user to press a key:</p> <pre><code> while read -r line;do echo \"$line\"; read -p \"Press any key\" -n 1;done &lt; file\n</code></pre> <p>And, surprise this doesn't work. Why? because the shell descriptor of the while loop looks like:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| file |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n</code></pre> <p>and our read inherits these descriptors, and our command (<code>read -p \"Press any key\" -n 1</code>) inherits them, and thus reads from file and not from our terminal.</p> <p>A quick look at <code>help read</code> tells us that we can specify a file descriptor from which <code>read</code> should read. Cool. Now let's use <code>exec</code> to get another descriptor:</p> <pre><code> exec 3&lt;file\n while read -u 3 line;do echo \"$line\"; read -p \"Press any key\" -n 1;done\n</code></pre> <p>Now the file descriptors look like:</p> <pre><code> --- +-----------------------+\nstandard input ( 0 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard output ( 1 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nstandard error ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-----------------------+\n\n --- +-----------------------+\nnew descriptor ( 3 ) ----&gt;| file |\n --- +-----------------------+\n</code></pre> <p>and it works.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#closing-the-file-descriptors","title":"Closing The File Descriptors","text":"<p>Closing a file through a file descriptor is easy, just make it a duplicate of -. For instance, let's close <code>stdin &lt;&amp;-</code> and <code>stderr 2&gt;&amp;-</code>:</p> <pre><code> bash -c '{ lsof -a -p $$ -d0,1,2 ;} &lt;&amp;- 2&gt;&amp;-'\n COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME\n bash 10668 pgas 1u CHR 136,2 4 /dev/pts/2\n</code></pre> <p>we see that inside the <code>{}</code> that only <code>1</code> is still here.</p> <p>Though the OS will probably clean up the mess, it is perhaps a good idea to close the file descriptors you open. For instance, if you open a file descriptor with <code>exec 3&gt;file</code>, all the commands afterwards will inherit it. It's probably better to do something like:</p> <pre><code>exec 3&gt;file\n.....\n#commands that uses 3\n.....\nexec 3&gt;&amp;-\n\n#we don't need 3 any more\n</code></pre> <p>I've seen some people using this as a way to discard, say stderr, using something like: command 2&gt;&amp;-. Though it might work, I'm not sure if you can expect all applications to behave correctly with a closed stderr.</p> <p>When in doubt, I use 2&gt;/dev/null.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#an-example","title":"An Example","text":"<p>This example comes from this post (ffe4c2e382034ed9) on the comp.unix.shell group:</p> <pre><code>{\n {\n cmd1 3&gt;&amp;- |\n cmd2 2&gt;&amp;3 3&gt;&amp;-\n } 2&gt;&amp;1 &gt;&amp;4 4&gt;&amp;- |\n cmd3 3&gt;&amp;- 4&gt;&amp;-\n\n} 3&gt;&amp;2 4&gt;&amp;1\n</code></pre> <p>The redirections are processed from left to right, but as the file descriptors are inherited we will also have to work from the outer to the inner contexts. We will assume that we run this command in a terminal. Let's start with the outer <code>{ } 3&gt;&amp;2 4&gt;&amp;1</code>.</p> <pre><code> --- +-------------+ --- +-------------+\n( 0 ) ----&gt;| /dev/pts/5 | ( 3 ) ----&gt;| /dev/pts/5 |\n --- +-------------+ --- +-------------+\n\n --- +-------------+ --- +-------------+\n( 1 ) ----&gt;| /dev/pts/5 | ( 4 ) ----&gt;| /dev/pts/5 |\n --- +-------------+ --- +-------------+\n\n --- +-------------+\n( 2 ) ----&gt;| /dev/pts/5 |\n --- +-------------+\n</code></pre> <p>We only made 2 copies of <code>stderr</code> and <code>stdout</code>. <code>3&gt;&amp;1 4&gt;&amp;1</code> would have produced the same result here because we ran the command in a terminal and thus <code>1</code> and <code>2</code> go to the terminal. As an exercise, you can start with <code>1</code> pointing to <code>file.stdout</code> and 2 pointing to <code>file.stderr</code>, you will see why these redirections are very nice.</p> <p>Let's continue with the right part of the second pipe: <code>| cmd3 3&gt;&amp;- 4&gt;&amp;-</code></p> <pre><code> --- +-------------+\n( 0 ) ----&gt;| 2nd pipe |\n --- +-------------+\n\n --- +-------------+\n( 1 ) ----&gt;| /dev/pts/5 |\n --- +-------------+\n\n --- +-------------+\n( 2 ) ----&gt;| /dev/pts/5 |\n --- +-------------+\n</code></pre> <p>It inherits the previous file descriptors, closes 3 and 4 and sets up a pipe for reading. Now for the left part of the second pipe <code>{...} 2&gt;&amp;1 &gt;&amp;4 4&gt;&amp;- |</code></p> <pre><code> --- +-------------+ --- +-------------+\n( 0 ) ----&gt;| /dev/pts/5 | ( 3 ) ----&gt;| /dev/pts/5 |\n --- +-------------+ --- +-------------+\n\n --- +-------------+\n( 1 ) ----&gt;| /dev/pts/5 |\n --- +-------------+\n\n --- +-------------+\n( 2 ) ----&gt;| 2nd pipe |\n --- +-------------+\n</code></pre> <p>First, The file descriptor <code>1</code> is connected to the pipe (<code>|</code>), then <code>2</code> is made a copy of <code>1</code> and thus is made an fd to the pipe (<code>2&gt;&amp;1</code>), then <code>1</code> is made a copy of <code>4</code> (<code>&gt;&amp;4</code>), then <code>4</code> is closed. These are the file descriptors of the inner <code>{}</code>. Lcet's go inside and have a look at the right part of the first pipe: <code>| cmd2 2&gt;&amp;3 3&gt;&amp;-</code></p> <pre><code> --- +-------------+\n( 0 ) ----&gt;| 1st pipe |\n --- +-------------+\n\n --- +-------------+\n( 1 ) ----&gt;| /dev/pts/5 |\n --- +-------------+\n\n --- +-------------+\n( 2 ) ----&gt;| /dev/pts/5 |\n --- +-------------+\n</code></pre> <p>It inherits the previous file descriptors, connects 0 to the 1<sup>st</sup> pipe, the file descriptor 2 is made a copy of 3, and 3 is closed. Finally, for the left part of the pipe:</p> <pre><code> --- +-------------+\n( 0 ) ----&gt;| /dev/pts/5 |\n --- +-------------+\n\n --- +-------------+\n( 1 ) ----&gt;| 1st pipe |\n --- +-------------+\n\n --- +-------------+\n( 2 ) ----&gt;| 2nd pipe |\n --- +-------------+\n</code></pre> <p>It also inherits the file descriptor of the left part of the 2<sup>nd</sup> pipe, file descriptor <code>1</code> is connected to the first pipe, <code>3</code> is closed.</p> <p>The purpose of all this becomes clear if we take only the commands:</p> <pre><code> cmd2\n\n --- +-------------+\n --&gt;( 0 ) ----&gt;| 1st pipe |\n / --- +-------------+\n /\n / --- +-------------+\n cmd 1 / ( 1 ) ----&gt;| /dev/pts/5 |\n / --- +-------------+\n /\n --- +-------------+ / --- +-------------+\n( 0 ) ----&gt;| /dev/pts/5 | / ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-------------+ / --- +-------------+\n /\n --- +-------------+ / cmd3\n( 1 ) ----&gt;| 1st pipe | /\n --- +-------------+ --- +-------------+\n ------------&gt;( 0 ) ----&gt;| 2nd pipe |\n --- +-------------+ / --- +-------------+\n( 2 ) ----&gt;| 2nd pipe |/\n --- +-------------+ --- +-------------+\n ( 1 ) ----&gt;| /dev/pts/5 |\n --- +-------------+\n\n --- +-------------+\n ( 2 ) ----&gt;| /dev/pts/5 |\n --- +-------------+\n</code></pre> <p>As said previously, as an exercise, you can start with <code>1</code> open on a file and <code>2</code> open on another file to see how the <code>stdin</code> from <code>cmd2</code> and <code>cmd3</code> goes to the original <code>stdin</code> and how the <code>stderr</code> goes to the original <code>stderr</code>.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#syntax","title":"Syntax","text":"<p>I used to have trouble choosing between <code>0&amp;&lt;3</code> <code>3&amp;&gt;1</code> <code>3&gt;&amp;1</code> <code>-&gt;2</code> <code>-&lt;&amp;0</code> <code>&amp;-&lt;0</code> <code>0&lt;&amp;-</code> etc... (I think probably because the syntax is more representative of the result, i.e., the redirection, than what is done, i.e., opening, closing, or duplicating file descriptors).</p> <p>If this fits your situation, then maybe the following \"rules\" will help you, a redirection is always like the following:</p> <pre><code> lhs op rhs\n</code></pre> <ul> <li> <p><code>lhs</code> is always a file description, i.e., a number:</p> <ul> <li>Either we want to open, duplicate, move or we want to close. If the op is <code>&lt;</code> then there is an implicit 0, if it's <code>&gt;</code> or <code>&gt;&gt;</code>, there is an implicit 1.</li> </ul> </li> <li> <p><code>op</code> is <code>&lt;</code>, <code>&gt;</code>, <code>&gt;&gt;</code>, <code>&gt;|</code>, or <code>&lt;&gt;</code>:</p> <ul> <li><code>&lt;</code> if the file decriptor in <code>lhs</code> will be read, <code>&gt;</code> if it will be written, <code>&gt;&gt;</code> if data is to be appended to the file, <code>&gt;|</code> to overwrite an existing file or <code>&lt;&gt;</code> if it will be both read and written.</li> </ul> </li> <li> <p><code>rhs</code> is the thing that the file descriptor will describe:</p> <ul> <li>It can be the name of a file, the place where another descriptor goes (<code>&amp;1</code>), or, <code>&amp;-</code>, which will close the file descriptor.</li> </ul> </li> </ul> <p>You might not like this description, and find it a bit incomplete or inexact, but I think it really helps to easily find that, say <code>&amp;-&gt;0</code> is incorrect.</p>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#a-note-on-style","title":"A note on style","text":"<p>The shell is pretty loose about what it considers a valid redirect. While opinions probably differ, this author has some (strong) recommendations:</p> <ul> <li>Always keep redirections \"tightly grouped\" -- that is, do not include whitespace anywhere within the redirection syntax except within quotes if required on the RHS (e.g. a filename that contains a space). Since shells fundamentally use whitespace to delimit fields in general, it is visually much clearer for each redirection to be separated by whitespace, but grouped in chunks that contain no unnecessary whitespace.</li> <li>Do always put a space between each redirection, and between the</li> <li>Always place redirections together at the very end of a command after all arguments. Never precede a command with a redirect. Never</li> <li>Never use the Csh <code>&amp;&gt;foo</code> and <code>&gt;&amp;foo</code> shorthand redirects. Use the long form <code>&gt;foo 2&gt;&amp;1</code>. (see: obsolete)</li> </ul> <pre><code># Good! This is clearly a simple commmand with two arguments and 4 redirections\ncmd arg1 arg2 &lt;myFile 3&lt;&amp;1 2&gt;/dev/null &gt;&amp;2\n\n# Good!\n{ cmd1 &lt;&lt;&lt;'my input'; cmd2; } &gt;someFile\n\n# Bad. Is the \"1\" a file descriptor or an argument to cmd? (answer: it's the FD). Is the space after the herestring part of the input data? (answer: No).\n# The redirects are also not delimited in any obvious way.\ncmd 2&gt;&amp; 1 &lt;&lt;&lt; stuff\n\n# Hideously Bad. It's difficult to tell where the redirects are and whether they're even valid redirects.\n# This is in fact one command with one argument, an assignment, and three redirects.\nfoo=bar&lt;baz bork&lt;&lt;&lt; blarg&gt;bleh\n</code></pre>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#conclusion","title":"Conclusion","text":"<p>I hope this tutorial worked for you.</p> <p>I lied, I did not explain <code>1&gt;&amp;3-</code>, go check the manual ;-)</p> <p>Thanks to St\u00e9phane Chazelas from whom I stole both the intro and the example....</p> <p>The intro is inspired by this introduction, you'll find a nice exercise there too:</p> <ul> <li>A Detailed Introduction to I/O and I/O Redirection</li> </ul> <p>The last example comes from this post:</p> <ul> <li>comp.unix.shell: piping stdout and stderr to different processes</li> </ul>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/redirection_tutorial/#see-also","title":"See also","text":"<ul> <li>Internal: Redirection syntax overview</li> </ul>","tags":["bash","shell","scripting","tutorial","redirection","redirect","file","descriptor"]},{"location":"howto/testing-your-scripts/","title":"Testing your scripts","text":"<p>The one of the simplest way to check your bash/sh scripts is run it and check it output or run it and check the result. This tutorial shows how-to use bashtest tool for testing your scripts.</p>"},{"location":"howto/testing-your-scripts/#write-simple-util","title":"Write simple util","text":"<p>We have a simple stat.sh script:</p> <pre><code>#!/usr/bin/env bash\n\nif [ -z \"$1\" ]\nthen\n DIR=./\nelse\n DIR=$1\nfi\n\necho \"Evaluate *.py statistics\"\nFILES=$(find $DIR -name '*.py' | wc -l)\nLINES=$((find $DIR -name '*.py' -print0 | xargs -0 cat) | wc -l)\necho \"PYTHON FILES: $FILES\"\necho \"PYTHON LINES: $LINES\"\n</code></pre> <p>This script evaluate the number of python files and the number of python code lines in the files. We can use it like <code>./stat.sh &lt;dir&gt;</code></p>"},{"location":"howto/testing-your-scripts/#create-testsuit","title":"Create testsuit","text":"<p>Then make test suits for stat.sh. We make a directory testsuit which contain test python files.</p> <p>testsuit/main.py</p> <pre><code>import foo\nprint(foo)\n</code></pre> <p>testsuit/foo.py</p> <pre><code>BAR = 1\nBUZ = BAR + 2\n</code></pre> <p>Ok! Our test suit is ready! We have 2 python files which contains 4 lines of code.</p>"},{"location":"howto/testing-your-scripts/#write-bashtests","title":"Write bashtests","text":"<p>Lets write tests. We just write a shell command for testing our work.</p> <p>Create file tests.bashtest:</p> <pre><code>$ ./stat.sh testsuit/\nEvaluate *.py statistics\nPYTHON FILES: 2\nPYTHON LINES: 4\n</code></pre> <p>This is our test! This is simple. Try to run it.</p> <pre><code># install bashtest if required!\n$ pip install bashtest\n\n# run tests\n$ bashtest *.bashtest\n1 items passed all tests:\n 1 tests in tests.bashtest\n1 tests in 1 items.\n1 passed and 0 failed.\nTest passed.\n</code></pre> <p>Thats all. We wrote one test. You can write more tests if you want.</p> <pre><code>$ ls testsuit/\nfoo.py main.py\n\n$ ./stat.sh testsuit/\nEvaluate *.py statistics\nPYTHON FILES: 2\nPYTHON LINES: 4\n</code></pre> <p>And run tests again:</p> <pre><code>$ bashtest *.bashtest\n1 items passed all tests:\n 2 tests in tests.bashtest\n2 tests in 1 items.\n2 passed and 0 failed.\nTest passed.\n</code></pre> <p>You can find more .bashtest examples in the bashtest github repo. You can also write your question or report a bug here.</p> <p>Happy testing!</p>"},{"location":"internals/shell_options/","title":"List of shell options","text":"<p>This information was taken from a Bash version \"<code>4.1</code>\", every now and then new options are added, so likely, this list isn't complete.</p> <p>The shell-options can be set with the shopt builtin command.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#shell-options","title":"Shell options","text":"","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#autocd","title":"autocd","text":"Option: <code>autocd</code> Since: 4.0-alpha Shell mode: interactive only Default: off <p>If set, a command name that is the name of a directory is executed as if it were the argument to the cd command.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#assoc_expand_once","title":"assoc_expand_once","text":"Option: <code>assoc_expand_once</code> Since: 5.0-alpha Shell mode: all Default: off <p>If set, Bash attempts to expand associative array options only once.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#cdable_vars","title":"cdable_vars","text":"Option: <code>cdable_vars</code> Since: unknown Shell mode: all Default: off <p>Treat every non-directory argument to the <code>cd</code>-command as variable name containing a directory to <code>cd</code> into.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#cdspell","title":"cdspell","text":"Option: <code>cdspell</code> Since: unknown Shell mode: interactive only Default: off <p>If set, minor errors in the spelling of a directory component in a cd command will be corrected. The errors checked for are transposed characters, a missing character, and one character too many. If a correction is found, the corrected file name is printed, and the command proceeds.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#checkhash","title":"checkhash","text":"Option: <code>checkhash</code> Since: unknown Shell mode: all Default: off <p>If set, Bash checks that a command found in the hash table exists before trying to execute it. If a hashed command no longer exists, a normal path search is performed.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#checkjobs","title":"checkjobs","text":"Option: <code>checkjobs</code> Since: 4.0-alpha Shell mode: interactive only Default: off <p>If set, Bash lists the status of any stopped and running jobs before exiting an interactive shell. If any jobs are running, this causes the exit to be deferred until a second exit is attempted without an intervening command. The shell always postpones exiting if any jobs are stopped.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#checkwinsize","title":"checkwinsize","text":"Option: <code>checkwinsize</code> Since: unknown Shell mode: all Default: on <p>If set, Bash checks the window size after each command and, if necessary, updates the values of the variables LINES and COLUMNS.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#cmdhist","title":"cmdhist","text":"Option: <code>cmdhist</code> Since: unknown Shell mode: all Default: off <p>If set, Bash attempts to save all lines of a multiple-line command in the same history entry. This allows easy re-editing of multi-line commands.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#compat31","title":"compat31","text":"Option: <code>compat31</code> Since: 3.2 Shell mode: all Default: off <p>Compatiblity mode for Bash 3.1</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#compat32","title":"compat32","text":"Option: <code>compat32</code> Since: 4.0 Shell mode: all Default: off <p>Compatiblity mode for Bash 3.2</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#compat40","title":"compat40","text":"Option: <code>compat40</code> Since: 4.1-beta Shell mode: all Default: off <p>Compatiblity mode for Bash 4.0</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#compat41","title":"compat41","text":"Option: <code>compat41</code> Since: 4.2-alpha Shell mode: all Default: off <p>Compatiblity mode for Bash 4.1</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#compat42","title":"compat42","text":"Option: <code>compat42</code> Since: 4.3-alpha Shell mode: all Default: off <p>Compatiblity mode for Bash 4.2</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#compat43","title":"compat43","text":"Option: <code>compat43</code> Since: 4.4-alpha Shell mode: all Default: off <p>Compatiblity mode for Bash 4.3</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#compat44","title":"compat44","text":"Option: <code>compat44</code> Since: 5.0-alpha Shell mode: all Default: off <p>Compatiblity mode for Bash 4.4</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#direxpand","title":"direxpand","text":"Option: <code>direxpand</code> Since: 4.3-alpha Shell mode: all Default: off (unless changed on compile-time with <code>--enable-direxpand-default</code>) <p>If set, bash replaces directory names with the results of word expansion when performing filename completion. This changes the contents of the readline editing buffer. If not set, bash attempts to preserve what the user typed.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#dirspell","title":"dirspell","text":"Option: <code>dirspell</code> Since: 4.0-alpha Shell mode: all Default: off <p>If set, Bash will perform spelling corrections on directory names to match a glob.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#dotglob","title":"dotglob","text":"Option: <code>dotglob</code> Since: unknown Shell mode: all Default: off <p>If set, Bash includes filenames beginning with a <code>.</code> (dot) in the results of pathname expansion.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#execfail","title":"execfail","text":"Option: <code>execfail</code> Since: unknown Shell mode: non-interactive Default: off <p>If set, a non-interactive shell will not exit if it cannot execute the file specified as an argument to the <code>exec</code>-builtin command. An interactive shell does not exit if <code>exec</code> fails.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#expand_aliases","title":"expand_aliases","text":"Option: <code>expand_aliases</code> Since: unknown Shell mode: all Default: on (interactive), off (non-interactive) <p>If set, aliases are expanded. This option is enabled by default for interactive shells.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#extdebug","title":"extdebug","text":"Option: <code>extdebug</code> Since: 3.0-alpha Shell mode: all Default: off <p>If set, behavior intended for use by debuggers is enabled.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#extglob","title":"extglob","text":"Option: <code>extglob</code> Since: 2.02-alpha1 Shell mode: all Default: off <p>If set, the extended pattern matching features are enabled. See the important note below under Parser configurations.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#extquote","title":"extquote","text":"Option: <code>extquote</code> Since: 3.0-alpha (?) Shell mode: all Default: on <p>If set, <code>$'string'</code> and <code>$\"string\"</code> quoting is performed within parameter expansions enclosed in double quotes. See the important note below under Parser configurations.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#failglob","title":"failglob","text":"Option: <code>failglob</code> Since: 3.0-alpha Shell mode: all Default: off <p>If set, patterns which fail to match filenames during pathname expansion result in an error message.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#force_fignore","title":"force_fignore","text":"Option: <code>force_fignore</code> Since: 3.0-alpha Shell mode: interactive Default: on <p>If set, the suffixes specified by the FIGNORE shell variable cause words to be ignored when performing word completion even if the ignored words are the only possible completions. This option is enabled by default.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#globasciiranges","title":"globasciiranges","text":"Option: <code>globasciiranges</code> Since: 4.3-alpha Shell mode: all Default: on (configurable at compile time) <p>If set, range expressions used in pattern matching behave as if in the traditional C locale when performing comparisons. That is, the current locale's collating sequence is not taken into account, so b will not collate between A and B, and upper-case and lower-case ASCII characters will collate together.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#globstar","title":"globstar","text":"Option: <code>globstar</code> Since: 4.0-alpha Shell mode: all Default: off <p>If set, recursive globbing with <code>**</code> is enabled.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#gnu_errfmt","title":"gnu_errfmt","text":"Option: <code>gnu_errfmt</code> Since: 3.0-alpha Shell mode: all Default: off <p>If set, shell error messages are written in the \"standard GNU error message format\".</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#histappend","title":"histappend","text":"Option: <code>histappend</code> Since: unknown Shell mode: interactive (?) Default: off <p>If set, the history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#histreedit","title":"histreedit","text":"Option: <code>histreedit</code> Since: unknown Shell mode: interactive (?) Default: off <p>If set, and readline is being used, a user is given the opportunity to re-edit a failed history substitution.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#histverify","title":"histverify","text":"Option: <code>histverify</code> Since: unknown Shell mode: interactive (?) Default: off <p>Allow to review a history substitution result by loading the resulting line into the editing buffer, rather than directly executing it.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#hostcomplete","title":"hostcomplete","text":"Option: <code>hostcomplete</code> Since: 2.0-alpha3 Shell mode: interactive (?) Default: on <p>If set, Bash completion also completes hostnames. On by default.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#huponexit","title":"huponexit","text":"Option: <code>huponexit</code> Since: 2.02-alpha1 Shell mode: interactive login Default: off <p>If set, Bash will send the <code>SIGHUP</code> signal to all jobs when an interactive login shell exits.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#interactive_comments","title":"interactive_comments","text":"Option: <code>interactive_comments</code> Since: unknown Shell mode: interactive Default: on <p>Allow commenting in interactive shells, on by default.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#lastpipe","title":"lastpipe","text":"Option: <code>lastpipe</code> Since: 4.2-alpha Shell mode: all Default: off <p>If set, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#lithist","title":"lithist","text":"Option: <code>lithist</code> Since: unknown Shell mode: interactive Default: off <p>If set, and the #cmdhist option is enabled, multi-line commands are saved to the history with embedded newlines rather than using semicolon separators where possible.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#localvar_inherit","title":"localvar_inherit","text":"Option: <code>localvar_inherit</code> Since: 5.0-alpha Shell mode: all Default: off <p>If this option is set, a local variable inherits the value of a variable with the same name at the nearest preceding scope.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#login_shell","title":"login_shell","text":"Option: <code>login_shell</code> Since: 2.05a-alpha1 Shell mode: all Default: n/a <p>The option is set when Bash is a login shell. This is a readonly option.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#mailwarn","title":"mailwarn","text":"Option: <code>mailwarn</code> Since: unknown Shell mode: interactive (?) Default: off <p>If set, and a file that Bash is checking for mail has been accessed since the last time it was checked, the message \"The mail in mailfile has been read\" is displayed.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#no_empty_cmd_completion","title":"no_empty_cmd_completion","text":"Option: <code>mailwarn</code> Since: unknown Shell mode: interactive (?) Default: off <p>If set, and readline is being used, Bash will not attempt to search the PATH for possible completions when completion is attempted on an empty line.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#nocaseglob","title":"nocaseglob","text":"Option: <code>nocaseglob</code> Since: 2.02-alpha1 Shell mode: all Default: off <p>If set, Bash matches filenames in a case-insensitive fashion when performing pathname expansion.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#nocasematch","title":"nocasematch","text":"Option: <code>nocasematch</code> Since: 3.1-alpha1 Shell mode: all Default: off <p>If set, Bash matches patterns in a case-insensitive fashion when performing matching while executing <code>case</code> or <code>[[</code> conditional commands.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#nullglob","title":"nullglob","text":"Option: <code>nullglob</code> Since: unknown Shell mode: all Default: off <p>If set, Bash allows patterns which match no files to expand to a null string, rather than themselves.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#progcomp","title":"progcomp","text":"Option: <code>progcomp</code> Since: 2.04-alpha1 Shell mode: interactive (?) Default: on <p>If set, the programmable completion facilities are enabled. This option is enabled by default.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#promptvars","title":"promptvars","text":"Option: <code>promptvars</code> Since: unknown Shell mode: interactive Default: on <p>If set, prompt strings undergo parameter expansion, command substitution, arithmetic expansion, and quote removal after being expanded using the prompt special sequences. This option is enabled by default.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#restricted_shell","title":"restricted_shell","text":"Option: <code>restricted_shell</code> Since: 2.03-alpha Shell mode: interactive (?) Default: off <p>The option is set when Bash is a restricted shell. This is a readonly option.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#shift_verbose","title":"shift_verbose","text":"Option: <code>shift_verbose</code> Since: unknown Shell mode: all Default: off, on in POSIX mode <p>If set, the shift builtin prints an error message when the shift count exceeds the number of positional parameters.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#sourcepath","title":"sourcepath","text":"Option: <code>sourcepath</code> Since: unknown Shell mode: all Default: on <p>If set, the source builtin command uses the value of PATH to find the directory containing the file supplied as an argument. This option is enabled by default.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#syslog_history","title":"syslog_history","text":"Option: <code>syslog_history</code> Since: 5.0-alpha Shell mode: unknown Default: off <p>If set, the shell history is sent to syslog.</p> <p>This option is undocumented and available only if the shell supports syslog.</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#xpg_echo","title":"xpg_echo","text":"Option: <code>xpg_echo</code> Since: 2.04-beta1 Shell mode: all Default: off <p>If set, the <code>echo</code>-builtin command expands backslash-escape sequences by default (POSIX, SUS, XPG).</p>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#parser-configurations","title":"Parser configurations","text":"<p>Parser configurations change the way the Bash parser recognizes the syntax when parsing a line. This, of course, is impossible for a line that already was parsed.</p> <p>There are two options that influence the parsing this way:</p> <ul> <li><code>extglob</code></li> <li><code>extquote</code></li> </ul> <p>Consequence: You can't use the new syntax (e.g. the extended globbing syntax) and the command to enable it in the same line.</p> <pre><code>$ shopt -s extglob; echo !(*.txt) # this is the WRONG way!\n-bash: syntax error near unexpected token `('\n</code></pre> <p>You have to configure the parser before a line with new syntax is parsed:</p> <pre><code>$ shopt -s extglob # standalone - CORRECT way!\n$ echo !(*.txt)\n...\n</code></pre>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"internals/shell_options/#see-also","title":"See also","text":"<ul> <li>Internal: shopt builtin command</li> <li>Internal: set builtin command</li> </ul>","tags":["bash","shell","scripting","options","runtime","variable","behaviour"]},{"location":"misc/bashphorisms/","title":"The Bashphorisms","text":"<p>Bashphorisms are aphorisms for the IRC channel <code>#bash</code> on Freenode. Keep in mind that this version is a snapshot, the bashphorisms are changed here and there. Also, another snapshot.</p> <p>I think <code>greycat</code> was the first one who had the idea, but I'm not sure.</p> <p>Our bashphorisms can be queried from <code>greybot</code> using <code>!bN</code>, where <code>N</code> is the bashphorism number.</p> <p>And yes, these bashphorisms reflect the daily reality in <code>#bash</code>.</p> Number Bashphorism 0 The questioner will never tell you what they are really doing the first time they ask. 1 The questioner's first description of the problem/question will be misleading. 2 The questioner will keep changing the question until it drives the helpers in the channel insane. 3 Offtopicness will continue until someone asks a bash question that falls under bashphorisms 1 and/or 2, and <code>greycat</code> gets pissed off. 4 The questioner will not read and apply the answers he is given but will instead continue to practice bashphorism #1 and bashphorism #2. 5 The ignorant will continually mis-educate the other noobies. 6 When given a choice of solutions, the newbie will always choose the wrong one. 7 The newbie will always find a reason to say, \"It doesn't work.\" 8 If you don't know to whom the bashphorism's referring, it's you. 9 All examples given by the questioner will be broken, misleading, wrong, and not representative of the actual question. 10 See B1 11 Please apply <code>(( % 10 ))</code> to the bashphorism value. 12 All logic is deniable; however, some logic will plonk you if you deny it. 13 Everyone ignores greycat when he is right. When he is wrong, it is !b1 14 The newbie doesn't actually know what he's asking. If he did, he wouldn't need to ask. 15 The more advanced you are, the more likely you are to be overcomplicating it. 16 The more beginner you are, the more likely you are to be overcomplicating it. 17 A newbie comes to #bash to get his script confirmed. He leaves disappointed. 18 The newbie will not accept the answer you give, no matter how right it is. 19 The newbie is a bloody loon. 20 The newbie will always have some excuse for doing it wrong. 21 When the newbie's question is ambiguous, the proper interpretation will be whichever one makes the problem the hardest to solve. 22 The newcomer will abuse the bot's factoid triggers for their own entertainment until someone gets annoyed enough to ask them to message it privately instead. 23 Everyone is a newcomer. 24 The newcomer will address greybot as if it were human. 25 The newbie won't accept any answer that uses practical or standard tools. 26 The newbie will not TELL you about this restriction until you have wasted half an hour. 27 The newbie will lie. 28 When the full horror of the newbie's true goal is revealed, the newbie will try to restate the goal to trick you into answering. Newbies are stupid. 29 It's always git. Or python virtualenv. Or docker. One of those pieces of shit. ALWAYS. 30 They won't show you the homework assignment. That would make it too easy. 31 Your teacher is a f**king idiot. 32 The more horrifyingly wrong a proposed solution is, the more likely it will be used. 33 The newbie cannot explain what he is doing, or why. He will show you incomprehensible, nonworking code instead. What? You can't read his mind?! <p>Please feel free to correct or extend this page whenever needed.</p>"},{"location":"misc/readthesourceluke/","title":"Readthesourceluke","text":"<p>Comments extracted from the bash source and therefore Copyright (C) 1987-2004 Free Software Foundation, Inc. under the terms of the GNU General Public License etc..</p> <p>from <code>mailcheck.c</code>:</p> <pre><code>/* check_mail () is useful for more than just checking mail. Since it has\n the paranoids dream ability of telling you when someone has read your\n mail, it can just as easily be used to tell you when someones .profile\n file has been read, thus letting one know when someone else has logged\n in. Pretty good, huh? */\n</code></pre> <p>From <code>builtins/read.def</code>:</p> <pre><code> /* If there are no variables, save the text of the line read to the\n variable $REPLY. ksh93 strips leading and trailing IFS whitespace,\n so that `read x ; echo \"$x\"' and `read ; echo \"$REPLY\"' behave the\n same way, but I believe that the difference in behaviors is useful\n enough to not do it. Without the bash behavior, there is no way\n to read a line completely without interpretation or modification\n unless you mess with $IFS (e.g., setting it to the empty string).\n If you disagree, change the occurrences of `#if 0' to `#if 1' below. */\n</code></pre> <p>from <code>variables.c</code>:</p> <pre><code> /*\n * 24 October 2001\n *\n * I'm tired of the arguing and bug reports. Bash now leaves SSH_CLIENT\n * and SSH2_CLIENT alone. I'm going to rely on the shell_level check in\n * isnetconn() to avoid running the startup files more often than wanted.\n * That will, of course, only work if the user's login shell is bash, so\n * I've made that behavior conditional on SSH_SOURCE_BASHRC being defined\n * in config-top.h.\n */\n</code></pre> <p>From <code>shell.h</code>:</p> <pre><code>/* Values that can be returned by execute_command (). */\n#define EXECUTION_FAILURE 1\n#define EXECUTION_SUCCESS 0\n\n/* Usage messages by builtins result in a return status of 2. */\n#define EX_BADUSAGE 2\n\n/* Special exit statuses used by the shell, internally and externally. */\n#define EX_RETRYFAIL 124\n#define EX_WEXPCOMSUB 125\n#define EX_BINARY_FILE 126\n#define EX_NOEXEC 126\n#define EX_NOINPUT 126\n#define EX_NOTFOUND 127\n\n#define EX_SHERRBASE 256 /* all special error values are &gt; this. */\n\n#define EX_BADSYNTAX 257 /* shell syntax error */\n#define EX_USAGE 258 /* syntax error in usage */\n#define EX_REDIRFAIL 259 /* redirection failed */\n#define EX_BADASSIGN 260 /* variable assignment error */\n#define EX_EXPFAIL 261 /* word expansion failed */\n</code></pre>"},{"location":"misc/shell_humor/","title":"Shell Humor","text":"<p>Nothing special, just my private collection of some more or less funny shell stuff I saw during the years.</p> <p>Usually Bash and/or Linux (GNU Toolset) specific.</p> <pre><code>$ %blow\n-bash: fg: %blow: no such job\n\n$ ar m god\nar: creating god\n\n$ touch /pussy\ntouch: cannot touch `/pussy': Permission denied\n\n$ mount; fsck; fsck; fsck; umount; sleep\n\n# the lover variant\n$ unzip; strip; touch; finger; grep; mount; fsck; more; yes; fsck; fsck; umount; sleep\n\n# it's not directly funny, only because it's not obvious that this is an sed command\n# for the &lt;&lt;&lt;, it works only in Bash\n$ sed streetlight &lt;&lt;&lt; reeter\nlighter\n\n# see above for comments\n$ sed statement &lt;&lt;&lt; cat\ncement\n\n$ (-\nbash: (-: command not found\n\n$ echo '[q]sa[ln0=aln256%Pln256/snlbx]sb3135071790101768542287578439snlbxq'|dc\nGET A LIFE!\n</code></pre>"},{"location":"scripting/bashbehaviour/","title":"Bash's behaviour","text":"<p>FIXME</p> <p>incomplete</p>","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashbehaviour/#bash-startup-modes","title":"Bash startup modes","text":"","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashbehaviour/#login-shell","title":"Login shell","text":"<p>As a \"login shell\", Bash reads and sets (executes) the user's profile from <code>/etc/profile</code> and one of <code>~/.bash_profile</code>, <code>~/.bash_login</code>, or <code>~/.profile</code> (in that order, using the first one that's readable!).</p> <p>When a login shell exits, Bash reads and executes commands from the file <code>~/.bash_logout</code>, if it exists.</p> <p>Why an extra login shell mode? There are many actions and variable sets that only make sense for the initial user login. That's why all UNIX\u00ae shells have (should have) a \"login\" mode.</p> <p>Methods to start Bash as a login shell:</p> <ul> <li>the first character of <code>argv[0]</code> is <code>-</code> (a hyphen): traditional UNIX\u00ae shells start from the <code>login</code> binary</li> <li>Bash is started with the <code>-l</code> option</li> <li>Bash is started with the <code>--login</code> option</li> </ul> <p>Methods to test for login shell mode:</p> <ul> <li>the shell option <code>login_shell</code> is set</li> </ul> <p>Related switches:</p> <ul> <li><code>--noprofile</code> disables reading of all profile files</li> </ul>","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashbehaviour/#interactive-shell","title":"Interactive shell","text":"<p>When Bash starts as an interactive non-login shell, it reads and executes commands from <code>~/.bashrc</code>. This file should contain, for example, aliases, since they need to be defined in every shell as they're not inherited from the parent shell.</p> <p>The feature to have a system-wide <code>/etc/bash.bashrc</code> or a similar system-wide rc-file is specific to vendors and distributors that ship their own, patched variant of Bash. The classic way to have a system-wide rc file is to <code>source /etc/bashrc</code> from every user's <code>~/.bashrc</code>.</p> <p>Methods to test for interactive-shell mode:</p> <ul> <li>the special parameter <code>$-</code> contains the letter <code>i</code> (lowercase I)</li> </ul> <p>Related switches:</p> <ul> <li><code>-i</code> forces the interactive mode</li> <li><code>--norc</code> disables reading of the startup files (e.g. <code>/etc/bash.bashrc</code> if supported) and <code>~/.bashrc</code></li> <li><code>--rcfile</code> defines another startup file (instead of <code>/etc/bash.bashrc</code> and <code>~/.bashrc</code>)</li> </ul>","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashbehaviour/#sh-mode","title":"SH mode","text":"<p>When Bash starts in SH compatiblity mode, it tries to mimic the startup behaviour of historical versions of <code>sh</code> as closely as possible, while conforming to the POSIX\u00ae standard as well. The profile files read are <code>/etc/profile</code> and <code>~/.profile</code>, if it's a login shell.</p> <p>If it's not a login shell, the environment variable ENV is evaluated and the resulting filename is used as the name of the startup file.</p> <p>After the startup files are read, Bash enters the POSIX\u00ae compatiblity mode (for running, not for starting!).</p> <p>Bash starts in <code>sh</code> compatiblity mode when:</p> <ul> <li>the base filename in <code>argv[0]</code> is <code>sh</code> (:!: NB: <code>/bin/sh</code> may be linked to <code>/bin/bash</code>, but that doesn't mean it acts like <code>/bin/bash</code> :!:)</li> </ul>","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashbehaviour/#posix-mode","title":"POSIX mode","text":"<p>When Bash is started in POSIX\u00ae mode, it follows the POSIX\u00ae standard for startup files. In this mode, interactive shells expand the ENV variable and commands are read and executed from the file whose name is the expanded value. No other startup files are read. Hence, a non-interactive shell doesn't read any startup files in POSIX\u00ae mode.</p> <p>Bash starts in POSIX\u00ae mode when:</p> <ul> <li>the commandline option <code>--posix</code> is specified</li> <li>the environment variable POSIXLY_CORRECT is set</li> </ul>","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashbehaviour/#quick-startup-file-reference","title":"Quick startup file reference","text":"<ul> <li>Eventual system-wide rc-files are usually read when <code>~/.bashrc</code> would be read (at least Debian GNU/Linux behaves like that)</li> <li>Regardless of the system-wide files in <code>/etc</code> which are always read, Bash usually reads the first file found, when multiple choices are given (for user files in <code>~/</code>)</li> </ul> Mode <code>/etc/profile</code> <code>~/.bash_profile</code> <code>~/.bash_login</code> <code>~/.profile</code> <code>~/.bashrc</code> <code>${ENV}</code> Login shell \u2705 \u2705 \u2705 \u2705 \ud83d\udeab \ud83d\udeab Interactive shell \ud83d\udeab \ud83d\udeab \ud83d\udeab \ud83d\udeab \u2705 \ud83d\udeab SH compatible login \u2705 \ud83d\udeab \ud83d\udeab \u2705 \ud83d\udeab \ud83d\udeab SH compatible \ud83d\udeab \ud83d\udeab \ud83d\udeab \ud83d\udeab \ud83d\udeab \u2705 POSIX\u00ae compatiblity \ud83d\udeab \ud83d\udeab \ud83d\udeab \ud83d\udeab \ud83d\udeab \u2705","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashbehaviour/#bash-run-modes","title":"Bash run modes","text":"","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashbehaviour/#normal-bash","title":"Normal Bash","text":"","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashbehaviour/#posix-run-mode","title":"POSIX run mode","text":"<p>In POSIX\u00ae mode, Bash follows the POSIX\u00ae standard regarding behaviour and parsing (excerpt from a Bash maintainer's document):</p> <pre><code>Starting Bash with the `--posix' command-line option or executing `set\n-o posix' while Bash is running will cause Bash to conform more closely\nto the POSIX standard by changing the behavior to match that specified\nby POSIX in areas where the Bash default differs.\n\nWhen invoked as `sh', Bash enters POSIX mode after reading the startup\nfiles.\n\nThe following lists what's changed when Bash is in `POSIX mode':\n\n 1. When a command in the hash table no longer exists, Bash will\n re-search `$PATH' to find the new location. This is also\n available with `shopt -s checkhash'.\n\n 2. The message printed by the job control code and builtins when a job\n exits with a non-zero status is `Done(status)'.\n\n 3. The message printed by the job control code and builtins when a job\n is stopped is `Stopped(SIGNAME)', where SIGNAME is, for example,\n `SIGTSTP'.\n\n 4. The `bg' builtin uses the required format to describe each job\n placed in the background, which does not include an indication of\n whether the job is the current or previous job.\n\n 5. Reserved words appearing in a context where reserved words are\n recognized do not undergo alias expansion.\n\n 6. The POSIX `PS1' and `PS2' expansions of `!' to the history number\n and `!!' to `!' are enabled, and parameter expansion is performed\n on the values of `PS1' and `PS2' regardless of the setting of the\n `promptvars' option.\n\n 7. The POSIX startup files are executed (`$ENV') rather than the\n normal Bash files.\n\n 8. Tilde expansion is only performed on assignments preceding a\n command name, rather than on all assignment statements on the line.\n\n 9. The default history file is `~/.sh_history' (this is the default\n value of `$HISTFILE').\n\n 10. The output of `kill -l' prints all the signal names on a single\n line, separated by spaces, without the `SIG' prefix.\n\n 11. The `kill' builtin does not accept signal names with a `SIG'\n prefix.\n\n 12. Non-interactive shells exit if FILENAME in `.' FILENAME is not\n found.\n\n 13. Non-interactive shells exit if a syntax error in an arithmetic\n expansion results in an invalid expression.\n\n 14. Redirection operators do not perform filename expansion on the word\n in the redirection unless the shell is interactive.\n\n 15. Redirection operators do not perform word splitting on the word in\n the redirection.\n\n 16. Function names must be valid shell names. That is, they may not\n contain characters other than letters, digits, and underscores, and\n may not start with a digit. Declaring a function with an invalid\n name causes a fatal syntax error in non-interactive shells.\n\n 17. POSIX special builtins are found before shell functions during\n command lookup.\n\n 18. If a POSIX special builtin returns an error status, a\n non-interactive shell exits. The fatal errors are those listed in\n the POSIX standard, and include things like passing incorrect\n options, redirection errors, variable assignment errors for\n assignments preceding the command name, etc.\n\n 19. If `CDPATH' is set, the `cd' builtin will not implicitly append\n the current directory to it. This means that `cd' will fail if no\n valid directory name can be constructed from any of the entries in\n `$CDPATH', even if the a directory with the same name as the name\n given as an argument to `cd' exists in the current directory.\n\n 20. A non-interactive shell exits with an error status if a variable\n assignment error occurs when no command name follows the assignment\n statements. A variable assignment error occurs, for example, when\n trying to assign a value to a readonly variable.\n\n 21. A non-interactive shell exits with an error status if the iteration\n variable in a `for' statement or the selection variable in a\n `select' statement is a readonly variable.\n\n 22. Process substitution is not available.\n\n 23. Assignment statements preceding POSIX special builtins persist in\n the shell environment after the builtin completes.\n\n 24. Assignment statements preceding shell function calls persist in the\n shell environment after the function returns, as if a POSIX\n special builtin command had been executed.\n\n 25. The `export' and `readonly' builtin commands display their output\n in the format required by POSIX.\n\n 26. The `trap' builtin displays signal names without the leading `SIG'.\n\n 27. The `trap' builtin doesn't check the first argument for a possible\n signal specification and revert the signal handling to the original\n disposition if it is, unless that argument consists solely of\n digits and is a valid signal number. If users want to reset the\n handler for a given signal to the original disposition, they\n should use `-' as the first argument.\n\n 28. The `.' and `source' builtins do not search the current directory\n for the filename argument if it is not found by searching `PATH'.\n\n 29. Subshells spawned to execute command substitutions inherit the\n value of the `-e' option from the parent shell. When not in POSIX\n mode, Bash clears the `-e' option in such subshells.\n\n 30. Alias expansion is always enabled, even in non-interactive shells.\n\n 31. When the `alias' builtin displays alias definitions, it does not\n display them with a leading `alias ' unless the `-p' option is\n supplied.\n\n 32. When the `set' builtin is invoked without options, it does not\n display shell function names and definitions.\n\n 33. When the `set' builtin is invoked without options, it displays\n variable values without quotes, unless they contain shell\n metacharacters, even if the result contains nonprinting characters.\n\n 34. When the `cd' builtin is invoked in LOGICAL mode, and the pathname\n constructed from `$PWD' and the directory name supplied as an\n argument does not refer to an existing directory, `cd' will fail\n instead of falling back to PHYSICAL mode.\n\n 35. When the `pwd' builtin is supplied the `-P' option, it resets\n `$PWD' to a pathname containing no symlinks.\n\n 36. The `pwd' builtin verifies that the value it prints is the same as\n the current directory, even if it is not asked to check the file\n system with the `-P' option.\n\n 37. When listing the history, the `fc' builtin does not include an\n indication of whether or not a history entry has been modified.\n\n 38. The default editor used by `fc' is `ed'.\n\n 39. The `type' and `command' builtins will not report a non-executable\n file as having been found, though the shell will attempt to\n execute such a file if it is the only so-named file found in\n `$PATH'.\n\n 40. The `vi' editing mode will invoke the `vi' editor directly when\n the `v' command is run, instead of checking `$FCEDIT' and\n `$EDITOR'.\n\n 41. When the `xpg_echo' option is enabled, Bash does not attempt to\n interpret any arguments to `echo' as options. Each argument is\n displayed, after escape characters are converted.\n\n\nThere is other POSIX behavior that Bash does not implement by default\neven when in POSIX mode. Specifically:\n\n 1. The `fc' builtin checks `$EDITOR' as a program to edit history\n entries if `FCEDIT' is unset, rather than defaulting directly to\n `ed'. `fc' uses `ed' if `EDITOR' is unset.\n\n 2. As noted above, Bash requires the `xpg_echo' option to be enabled\n for the `echo' builtin to be fully conformant.\n\n\nBash can be configured to be POSIX-conformant by default, by specifying\nthe `--enable-strict-posix-default' to `configure' when building.\n</code></pre> <p>FIXME</p> <p>help me to find out what breaks in POSIX\u00ae mode!</p> <p>The POSIX\u00ae mode can be switched on by:</p> <ul> <li>Bash starting as <code>sh</code> (the basename of <code>argv[0]</code> is <code>sh</code>)</li> <li>starting Bash with the commandline option <code>--posix</code></li> <li>on startup, the environment variable POSIXLY_CORRECT is set</li> <li>the command <code>set -o posix</code></li> </ul> <p>Tests for the POSIX\u00ae mode:</p> <ul> <li>the variable SHELLOPTS contains <code>posix</code> in its list</li> </ul>","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashbehaviour/#restricted-shell","title":"Restricted shell","text":"<p>In restricted mode, Bash sets up (and runs) a shell environment that's far more controlled and limited than the standard shell mode. It acts like normal Bash with the following restrictions:</p> <ul> <li>the <code>cd</code> command can't be used to change directories</li> <li>the variables SHELL, PATH, ENV and BASH_ENV can't be set or unset</li> <li>command names that contain a <code>/</code> (slash) can't be called (hence you're limited to <code>PATH</code>)</li> <li>filenames containing a <code>/</code> (slash) can't be specified as argument to the <code>source</code> or <code>.</code> builtin command</li> <li>filenames containing a <code>/</code> (slash) can't be specified as argument to the <code>-p</code> option of the <code>hash</code> builtin command</li> <li>function definitions are not inherited from the environment at shell startup</li> <li>the environment variable SHELLOPTS is ignored at startup</li> <li>redirecting output using the <code>&gt;</code>, <code>&gt;|</code>, <code>&lt;&gt;</code>, <code>&gt;&amp;</code>, <code>&amp;&gt;</code>, and <code>&gt;&gt;</code> redirection operators isn't allowed</li> <li>the <code>exec</code> builtin command can't replace the shell with another process</li> <li>adding or deleting builtin commands with the <code>-f</code> and <code>-d</code> options to the enable builtin command is forbidden</li> <li>using the <code>enable</code> builtin command to enable disabled shell builtins doesn't work</li> <li>the <code>-p</code> option to the <code>command</code> builtin command doesn't work</li> <li>turning off restricted mode with <code>set +r</code> or <code>set +o restricted</code> is (of course) forbidden</li> </ul> <p>The \"-r\" restrictions are turned on after Bash has read its startup files.</p> <p>When the command that is run is a shell script, then the restrictions are turned off for the (sub-)shell that runs that shell script.</p> <p>The restricted shell can be switched on by:</p> <ul> <li>calling Bash as <code>rbash</code> (the basename of <code>argv[0]</code> is <code>rbash</code>)</li> <li>calling Bash with the <code>-r</code> option</li> <li>calling Bash with the <code>--restricted</code> option</li> </ul> <p>Tests for restricted mode:</p> <ul> <li>the special parameter <code>$-</code> contains the letter <code>r</code> (lowercase R)</li> <li>the shell option <code>restricted_shell</code> is set and can be checked by the <code>shopt</code> builtin command</li> </ul>","tags":["bash","shell","scripting","startup","files","dotfiles","modes","POSIX"]},{"location":"scripting/bashchanges/","title":"Bash changes","text":"<p>This article is an incomplete overview of changes to Bash over time. Not all changes are listed, just the ones most likely to be useful for normal scripting. The overviews are categorized by topic and ordered by version.</p> <p>A useful starting point is the NEWS file in bash sources. If you have more detailed information, or historical information about Bash versions earlier than V2, feel free to mail me, or use the discussion below.</p> <p>Status: 5.1 (alpha)</p>"},{"location":"scripting/bashchanges/#shell-options","title":"Shell options","text":"<p>Note that the <code>shopt</code> builtin command first appeared in Bash 2.0.</p> <p>For this topic, see also</p> <ul> <li>shell_options</li> <li>set</li> </ul> Feature or change description Appeared in Bash version See also/remarks <code>posix</code> (for <code>set -o</code>) 1.14.0 <code>hostcomplete</code> 2.0-alpha3 <code>expand_aliases</code> 2.0 <code>huponexit</code> 2.02-alpha1 <code>nocaseglob</code> 2.02-alpha1 <code>extglob</code> 2.02-alpha1 together with extended globbing, KSH88 <code>restricted_shell</code> 2.03-alpha <code>xpg_echo</code> 2.04-beta1 <code>progcomp</code> 2.04-alpha1 <code>no_empty_command_completion</code> 2.04 <code>login_shell</code> 2.05a-alpha1 <code>nolog</code> (for <code>set -o</code>) 2.05a <code>gnu_errfmt</code> 3.0-alpha <code>force_fignore</code> 3.0-alpha <code>failglob</code> 3.0-alpha <code>extquote</code> 3.0-alpha unsure -- verify! <code>extdebug</code> 3.0-alpha <code>pipefail</code> (for <code>set -o</code>) 3.0 <code>functrace</code> (for <code>set -o</code>) 3.0 <code>errtrace</code> (for <code>set -o</code>) 3.0 <code>nocasematch</code> 3.1-alpha1 <code>dirspell</code> 4.0-alpha <code>globstar</code> 4.0-alpha <code>checkjobs</code> 4.0-alpha <code>autocd</code> 4.0-alpha <code>set -e</code> effects more intuitive 4.0 not directly specified by POSIX, but in consensus with POSIX WG <code>compat40</code> 4.1-beta <code>lastpipe</code> 4.2-alpha only works with job control disabled <code>compat41</code> 4.2-alpha <code>globasciiranges</code> 4.3-alpha enable \"character range globbing\" to always act as if in <code>C</code> locale <code>compat42</code> 4.3-alpha <code>compat43</code> 4.4-alpha <code>compat44</code> 5.0-alpha <code>localvar_inherit</code> 5.0-alpha local variables inherit preceeding scope values if they have the same name <code>syslog_history</code> 5.0-alpha send history lines to syslog (undocumented, default off) if syslog is supported <code>assoc_expand_once</code> 5.0-alpha expand associative array subscripts only one <code>globasciiranges</code> 5.0-beta New default: on (default may be configured at compile time) <code>localvar_inherit</code> 5.0-beta guard code against inheriting from an incompatible data type <code>checkwinsize</code> 5.0-beta2 New default: on <code>shift_verbose</code> 5.0-beta2 Default on when in POSIX mode"},{"location":"scripting/bashchanges/#general-allmany-builtins","title":"General (all/many builtins)","text":"Feature or change description Appeared in Bash version See also/remarks generally return 2 on usage error 2.0 generally accept <code>--</code> (end of options) 2.0 (where applicable) implement a <code>-p</code> option to produce reusable output 2.0 <code>shopt</code> and <code>umask</code> builtins were fixed to support that in 2.02"},{"location":"scripting/bashchanges/#printf","title":"printf","text":"<p>For this topic, see also</p> <ul> <li>printf</li> </ul> Feature or change description Appeared in Bash version See also/remarks new <code>printf</code> command 2.02-alpha1 respects <code>0..</code> and <code>0x..</code> prefixed numbers 2.04-beta1 consistency with arithmetic POSIX\u00ae length specifiers <code>j</code>, <code>t</code> and <code>z</code> 2.05a-alpha1 ISO C99 POSIX\u00ae flag <code>'</code> 2.05a-alpha1 conversion <code>a</code> and <code>A</code> 2.05a-rc1 if provided by the underlying printf(3) conversion <code>F</code> 2.05a-rc1 conversion <code>n</code> 2.05a-rc1 new option <code>-v</code> 3.1-alpha1 escape sequences <code>\\\"</code> and <code>\\?</code> 3.0-beta1 modified option <code>-v</code> to assign to individual array elements 4.1-alpha conversion <code>(...)T</code> 4.2-alpha support stftime(3) date/time format; uses current time <code>\\uNNNN</code> and <code>\\UNNNNNNNN</code> escape sequences 4.2-alpha for: <code>printf</code>, <code>echo -e</code>, <code>$'...'</code>"},{"location":"scripting/bashchanges/#conditional-expressions-and-test-command","title":"Conditional expressions and test command","text":"<p>For this topic, see also</p> <ul> <li>conditional_expression</li> <li>classictest</li> </ul> Feature or change description Appeared in Bash version See also/remarks <code>test</code>: <code>-o</code>, <code>==</code>, <code>&lt;</code> and <code>&gt;</code> 2.0 <code>test</code>: <code>-N</code> 2.02 <code>[[...]]</code>: new 2.02-alpha1 KSH93 <code>[[...]]</code>: regex support (<code>=~</code>) 3.0-alpha <code>[[...]]</code>: quotable right-hand-side of <code>=~</code> forces string matching 3.2-alpha for consistency with pattern matching <code>[[...]]</code>: <code>&lt;</code> and <code>&gt;</code> operators respect locale 4.1-alpha for consistency, since 4.1-beta: ensure you have set compatiblity to &gt;4.0 (default) <code>test</code>/<code>[</code>/<code>[[</code>: <code>-v</code> 4.2-alpha check if a variable is set <code>test</code>/<code>[</code>/<code>[[</code>: <code>-v</code> 4.2-alpha support array syntax to check for elements <code>test</code>/<code>[</code>/<code>[[</code>: <code>-N</code> accepts nanoseconds 5.1-alpha <code>test</code>/<code>[</code>/<code>[[</code>: <code>-v</code> accepts positional parameters 5.1-alpha"},{"location":"scripting/bashchanges/#other-builtins-and-keywords","title":"Other builtins and keywords","text":"Builtin Feature or change description Appeared in Bash version See also/remarks <code>bashbug</code> new 1.14.0 <code>select</code> new 1.14.0 <code>disown</code> new 2.0 <code>shopt</code> new 2.0 shopt <code>declare</code> new options <code>-a</code> and <code>-F</code> 2.0 <code>enable</code> builtin has basic plugin support (dlopen) 2.0 <code>exec</code> options <code>-l</code>, <code>-c</code> and <code>-a</code> 2.0 <code>read</code> options <code>-p</code>, <code>-e</code> and <code>-a</code> 2.0 read <code>readonly</code> option <code>-a</code> 2.0 arrays <code>time</code> new keyword 2.0 <code>shopt</code> <code>-p</code> (reusable output) 2.02 <code>umask</code> <code>-p</code> (reusable output) 2.02 <code>complete</code> new 2.04-devel for and together with support for programmable completion <code>compgen</code> new 2.04-devel for and together with support for programmable completion <code>read</code> options <code>-t</code>, <code>-n</code>, <code>-d</code>, <code>-s</code> 2.04-devel read <code>for ((...;...;...))</code> new 2.04-devel KSH93 <code>set</code> print shell functions in a format reusable as input 2.05-beta1 <code>for</code> allow an empty word list 2.05a-alpha1 <code>read</code> new option <code>-u</code> 2.05b-alpha1 read <code>caller</code> new 3.0 caller <code>coproc</code> new 4.0-alpha <code>declare</code> new options <code>-l</code> and <code>-u</code> 4.0-alpha together with case-changing expansion forms <code>case</code> new action list terminators '';;&amp; and '';&amp; 4.0-alpha ksh93: only <code>;&amp;</code>. zsh and mksh: <code>;|</code>. mksh: all 4, (<code>;;&amp;</code> is undocumented Bash compatibility) <code>read</code> changed <code>-t</code> (fractional seconds) 4.0-alpha <code>mapfile</code> new 4.0-alpha <code>read</code> new option <code>-i</code> 4.0-alpha <code>compopt</code> new 4.0-alpha <code>read</code> modified option <code>-t</code> to test for data 4.0-beta <code>read</code> new option <code>-N</code> 4.1-alpha <code>mapfile</code> changed behaviour regarding history spamming 4.1-alpha <code>declare</code> new option <code>-g</code> 4.2-alpha <code>mapfile</code> calls the callback with an additional argument: The line (data) 4.2-alpha <code>cd</code> new option <code>-e</code> 4.2-alpha <code>echo</code> <code>\\uNNNN</code> and <code>\\UNNNNNNNN</code> escape sequences 4.2-alpha for: <code>printf</code>, <code>echo -e</code>, <code>$'...'</code> <code>exec</code> option <code>-a</code> to give a <code>argv[0]</code> string 4.2-alpha <code>time</code> allowed as a command by itself to display timing values of the shell and its children 4.2-alpha POSIX change <code>help</code> <code>help</code> now searches exact topic-strings (i.e. <code>help read</code> won't find <code>readonly</code> anymore) 4.3-alpha <code>return</code> accept negative values as return value (e.g. <code>return -1</code> will show as (8 bit) 255 in the caller) 4.3-alpha <code>exit</code> accept negative values as return value (e.g. <code>return -1</code> will show as (8 bit) 255 in the caller) 4.3-alpha <code>read</code> <code>read</code> skips <code>NUL</code> (ASCII Code 0) in input 4.3-alpha <code>declare</code> new option <code>-n</code>/<code>+n</code> to support nameref variable type 4.3-alpha <code>wait</code> new option <code>-n</code> to wait for the next background job to finish, returning its exit status. 4.3-alpha <code>read</code> <code>read</code> checks first variable argument for validity before trying to read inout 4.3-beta <code>help</code> attempts substring matching (as it did through bash-4.2) if exact string matching fails 4.3-beta2 <code>fc</code> interprets option <code>-0</code> (zero) as the current command line 4.3-beta2 <code>cd</code> new option <code>-@</code> to browse a file's extended attributes (on systems that support <code>O_XATTR</code>) 4.3-rc1 <code>kill</code> new option <code>-L</code> (upper case ell) to list signals like the normal lowercase option <code>-l</code> (compatiblity with some standalone <code>kill</code> commands) 4.4-beta <code>mapfile</code> new option <code>-d</code> 4.4-alpha <code>wait</code> new option <code>-f</code> 5.0-alpha <code>history</code> option <code>-d</code> allows negative numbers to index from the end of the history list 5.0-alpha <code>umask</code> allows modes greater than octal 777 5.0-alpha <code>times</code> honors current locale settings when printing decimal points 5.0-alpha <code>kill</code> New options <code>-n SIGNUMBER</code> and <code>-s SIGNAME</code> 5.0-beta2 kill <code>select</code> Support for an empty wordlist following <code>in</code> 5.0-beta2 <code>read</code> Option <code>-e</code> (use ReadLine to obtain input) now works with arbitrary file descriptors (given by <code>-u</code> option) 5.1-alpha <code>trap</code> <code>-p</code> option prints signals with SIG_DFL/SIG_IGN on shell start (POSIX mode) 5.1-alpha <code>unset</code> automatically tries to unset a function if the given name is an invalid variable name 5.1-aplha <code>wait</code> option <code>-n</code> now accepts a list of jobs 5.1-alpha <code>wait</code> new option <code>-p NAME</code> to store PID/JobID (useful when waiting for a list of jobs) 5.1-alpha <code>local</code> new option <code>-p</code> to print local variables in the current scope 5.1-alpha <code>ulimit</code> new option <code>-R</code> to get/set <code>RLIMIT_RTTIME</code> resource 5.1-alpha"},{"location":"scripting/bashchanges/#builtin-variables","title":"Builtin variables","text":"Feature or change description Appeared in Bash version See also <code>HISTCMD</code> 1.14.0 interactive usage <code>PS1</code>, <code>PS2</code>, <code>PATH</code>, and <code>IFS</code> are unsettable 2.0 <code>DIRSTACK</code> array variable 2.0 <code>PIPESTATUS</code> array variable 2.0 <code>BASH_VERSINFO</code> array variable 2.0 <code>HOSTNAME</code> 2.0 <code>SHELLOPTS</code> 2.0 <code>MACHTYPE</code> 2.0 <code>GLOBIGNORE</code> 2.0 <code>HISTIGNORE</code> 2.0 respect <code>LC_ALL</code> 2.0 respect <code>LC_MESSAGES</code> 2.0 respect <code>LC_CTYPE</code> 2.0 respect <code>LC_COLLATE</code> 2.0 respect <code>LANG</code> 2.0 <code>GROUPS</code> array variable 2.01 <code>GROUPS</code> unsettable/takes (discarded) assignments 2.04 <code>FUNCNAME</code> 2.04 respect <code>LC_NUMERIC</code> 2.04 <code>TMOUT</code> 2.05b <code>BASH_REMATCH</code> 3.0 together with regex support in <code>[[...]]</code> <code>BASH_ARGC</code> 3.0 debugger support <code>BASH_ARGV</code> 3.0 debugger support <code>BASH_SOURCE</code> 3.0 debugger support <code>BASH_LINENO</code> 3.0 debugger support <code>BASH_SUBSHELL</code> 3.0 debugger support <code>BASH_EXECUTION_STRING</code> 3.0 debugger support <code>BASH_COMMAND</code> 3.0 debugger support <code>HISTTIMEFORMAT</code> 3.0 <code>COMP_WORDBREAKS</code> 3.0 respect <code>LC_TIME</code> 3.1 <code>BASHPID</code> 4.0-alpha Added to mksh R41. <code>PROMPT_DIRTRIM</code> 4.0 <code>BASH_XTRACEFD</code> 4.1-alpha <code>BASHOPTS</code> 4.1-alpha <code>FUNCNEST</code> 4.2-alpha <code>HISTSIZE</code> 4.3-alpha can be set to negative values for unlimited history length <code>HISTFILESIZE</code> 4.3-alpha can be set to negative values for unlimit history file size <code>CHILD_MAX</code> 4.3-alpha max. number of exit status of children the shell remembers <code>BASH_COMPAT</code> 4.3-alpha set shell compatiblity levels <code>EPOCHSECONDS</code> 5.0-alpha expands to the time in seconds since Unix epoch <code>EPOCHREALTIME</code> 5.0-alpha expands to the time in seconds since Unix epoch with microsecond granularity <code>BASH_ARGV0</code> 5.0-alpha get/set <code>$0</code> <code>PATH</code> 5.0-alpha Possibility to set a static path for use in a restricted shell (at compile time) <code>HISTSIZE</code> 5.0-beta Default can now be set at runtime <code>SRANDOM</code> 5.1-alpha New random generator for 32bit numbers (using various methods in the backend) <code>ARGV0</code> 5.1-alpha Respected when set in initial shell environment, then initially used to set <code>$0</code> <code>BASH_REMATCH</code> 5.1-alpha Not readonly anymore <code>PROMPT_COMMANDS</code> 5.1-alpha New array variable. List of commands to be executed like <code>PROMPT_COMMAND</code> <code>SECONDS</code> 5.1-alpha Assignment using arithmetic expressions (is nominally an integer variabnle) <code>RANDOM</code> 5.1-alpha Assignment using arithmetic expressions (is nominally an integer variabnle) <code>LINENO</code> 5.1-alpha Not an integer variabe"},{"location":"scripting/bashchanges/#quoting-expansions-substitutions-and-related","title":"Quoting, expansions, substitutions and related","text":"<p>For this topic, see also</p> <ul> <li>pe.</li> </ul> Feature or change description Appeared in Bash version Remarks Support for integer-indexed arrays 2.0 relevant builtins also got array support <code>${PARAMETER//PATTERN/REPLACEMENT}</code> 2.0 <code>${PARAMETER:OFFSET:LENGTH}</code> 2.0 <code>${!PARAMETER}</code> (indirection) 2.0 <code>$\"...\"</code> (localized strings) 2.0 <code>$'...'</code> (ANSI-C-like strings) 2.0 <code>\\xNNN</code> in <code>$'...'</code> (and <code>echo -e</code>) 2.02-alpha1 <code>$(&lt; FILENAME)</code> (file content) 2.02-alpha1 globbing (<code>fnmatch()</code>) capable of POSIX\u00ae character classes etc. 2.02-alpha1 extended globbing 2.02-alpha1 KSH88 globbing inside array mass-assignment: <code>ARRAY=(*.txt)</code> 2.03-alpha <code>$'...\\'...'</code> escaped single quote inside ANSI-C-like strings 2.04-devel KSH93 <code>${!PREFIX*}</code> (parameter name expansion) 2.04 KSH93 <code>$'...'</code> expands <code>\\cx</code> (Control-x) 2.05b <code>[:class:]</code> syntax for pattern matching 2.05b KSH93 <code>${!ARRAY[@]}</code> (array index expansion) 3.0-alpha KSH93 <code>{x..y}</code> (range brace expansion) 3.0-alpha <code>$'...'</code> expands <code>\\xNNN</code> (Hexdigits) 3.0 <code>+=</code> operator for arrays and strings 3.1-alpha1 <code>${PARAMETER//PATTERN/REPLACEMENT}</code> behaviour changed 3.2-alpha anchoring for global substitution is no longer allowed, changes the way old syntax may work <code>${@:0:x}</code> includes <code>$0</code> 4.0-alpha Support for associative arrays 4.0-alpha relevant builtins also got associative array support case modification operators for expansions 4.0-alpha <code>{0x..0y}</code> (zeropadding brace expansion) 4.0-alpha numerically indexed arrays can be accessed (on expansion time) from the end using negative indexes 4.1-alpha <code>\\uNNNN</code> and <code>\\uNNNNNNNN</code> in <code>$'...'</code> 4.2-alpha for: <code>printf</code>, <code>echo -e</code>, <code>$'...'</code> <code>${PARAMETER:OFFSET:LENGTH}</code>: Negative <code>LENGTH</code> values are used as offset from the end of the string 4.2-alpha Substrings only for Bash and ksh93. Works also for argument expansions in zsh. ksh93 can use <code>${arr[n..-m]}</code>. Word expansions like <code>${foo##bar}</code> understand indirect variable references 4.3-beta Transformations 4.4 Process substitution now works in POSIX mode 5.1-alpha New transformations: <code>U</code>, <code>u</code>, <code>L</code> 5.1-alpha Case-transformation New transformation: <code>K</code> 5.1-alpha Display associative arrays as key/value pairs"},{"location":"scripting/bashchanges/#arithmetic","title":"Arithmetic","text":"<p>For this topic, see also</p> <ul> <li>arith_expr</li> <li>arith</li> </ul> Feature or change description Appeared in Bash version Remarks <code>((...))</code> 2.0-beta2 KSH93 ternary operator 2.0 base 64 integer constants 2.0 the max. base before is unknown. Anybody? deprecated <code>$[...]</code> in favor of <code>$((...))</code> 2.0 exponentiaition operator (<code>**</code>) 2.02-alpha1 comma operator <code>EXPR,EXPR</code> 2.04-devel pre- and postfix operators 2.04-devel"},{"location":"scripting/bashchanges/#redirection-and-related","title":"Redirection and related","text":"<p>For this topic, see also</p> <ul> <li>redirection</li> </ul> Feature or change description Appeared in Bash version Remarks socket redirection (<code>/dev/tcp/</code>, <code>/dev/udp/</code>) 2.04-devel OS/filesystem-independent support for <code>/dev/std(in|out|err)</code> and <code>/dev/fd/*</code> 2.04 socket redirection accepts service names 2.05 <code>[n]&lt;&amp;word-</code> and <code>[n]&gt;&amp;word-</code> FD-duplicate/closing 2.05b-alpha1 KSH93 Here strings: <code>&lt;&lt;&lt; WORD</code> 2.05b-alpha1 <code>|&amp;</code> (synonym for <code>2&gt;&amp;1|</code>) 4.0-alpha <code>&amp;&gt;&gt;</code> (equiv. to <code>&gt;&gt;FILE 2&gt;&amp;1</code>) 4.0-alpha <code>{varname}</code> style automatic file descriptor allocation 4.1-alpha ksh93 <code>{varname[idx]}</code> fd allocation accepts array subscripts and special-meaning variables 4.3-alpha ksh93"},{"location":"scripting/bashchanges/#misc","title":"Misc","text":"Feature or change description Appeared in Bash version See also/remarks <code>DEBUG</code> trap 2.0 <code>ERR</code> trap 2.05a KSH93 Support for multibyte characters: Unicode / UTF8 2.05b <code>RETURN</code> trap 3.0 ksh93 <code>EXIT</code> trap evaluates in caller scope (for <code>function name {</code>). Bash <code>RETURN</code> in same scope. <code>command_not_found_handle</code> handler function 4.0-alpha official introduction of switchable \"compatiblity levels\" 4.0-alpha <code>compat31</code> was introduced in a 3.2 version, mainly because of the incompatibilities that were introduced by the changed <code>=~</code> operator <code>[[...]]</code> and <code>((...))</code> conditional commands are subject to the <code>ERR</code> trap and <code>set -e</code> feature 4.1-alpha ACL support for file status checks 4.1-alpha Assignment to negative array indices 4.3-alpha ksh93, zsh <code>declare</code>/<code>typeset -n</code> 4.3-alpha Support for nameref variable type, a variable referencing another one by name shells started to run process substitutions now run any trap set on <code>EXIT</code> 4.3-beta process substitution does not inherit the <code>v</code> flag 5.0-alpha <code>ERR</code> trap 5.0-alpha Reports more reliable line numbers Variable assignment 5.0-beta Assignments preceeding a special builtin that chages variable attributes are not propagated back unless compatiblity mode is 44 or lower"},{"location":"scripting/basics/","title":"The basics of shell scripting","text":"","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/basics/#script-files","title":"Script files","text":"<p>A shell script usually resides inside a file. The file can be executable, but you can call a Bash script with that filename as a parameter:</p> <pre><code>bash ./myfile\n</code></pre> <p>There is no need to add a boring filename extension like <code>.bash</code> or <code>.sh</code>. That is a holdover from UNIX\u00ae, where executables are not tagged by the extension, but by permissions (filemode). The file name can be any combination of legal filename characters. Adding a proper filename extension is a convention, nothing else.</p> <pre><code>chmod +x ./myfile\n</code></pre> <p>If the file is executable, and you want to use it by calling only the script name, the shebang must be included in the file.</p>","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/basics/#the-shebang","title":"The Shebang","text":"<p>The in-file specification of the interpreter of that file, for example:</p> <pre><code>#!/bin/bash\necho \"Hello world...\"\n</code></pre> <p>This is interpreted by the kernel <sup>1</sup> of your system. In general, if a file is executable, but not an executable (binary) program, and such a line is present, the program specified after <code>#!</code> is started with the scriptname and all its arguments. These two characters <code>#</code> and <code>!</code> must be the first two bytes in the file!</p> <p>You can follow the process by using <code>echo</code> as a fake interpreter:</p> <pre><code>#!/bin/echo\n</code></pre> <p>We don't need a script body here, as the file will never be interpreted and executed by \"<code>echo</code>\". You can see what the Operating System does, it calls \"<code>/bin/echo</code>\" with the name of the executable file and following arguments.</p> <pre><code>$ /home/bash/bin/test testword hello\n/home/bash/bin/test testword hello\n</code></pre> <p>The same way, with <code>#!/bin/bash</code> the shell \"<code>/bin/bash</code>\" is called with the script filename as an argument. It's the same as executing \"<code>/bin/bash /home/bash/bin/test testword hello</code>\"</p> <p>If the interpreter can be specified with arguments and how long it can be is system-specific (see #!-magic). When Bash executes a file with a #!/bin/bash shebang, the shebang itself is ignored, since the first character is a hashmark \"<code>#</code>\", which indicates a comment. The shebang is for the operating system, not for the shell. Programs that don't ignore such lines, may not work as shebang driven interpreters.</p> <p>Warning</p> <p>Attention:When the specified interpreter is unavailable or not executable (permissions), you usually get a \"<code>bad interpreter</code>\" error message., If you get nothing and it fails, check the shebang. Older Bash versions will respond with a \"<code>no such file or directory</code>\" error for a nonexistant interpreter specified by the shebang.</p> <p>Additional note: When you specify <code>#!/bin/sh</code> as shebang and that's a link to a Bash, then Bash will run in POSIX\u00ae mode! See:</p> <ul> <li>Bash behaviour.</li> </ul> <p>A common method is to specify a shebang like</p> <pre><code>#!/usr/bin/env bash\n</code></pre> <p>...which just moves the location of the potential problem to</p> <ul> <li>the <code>env</code> utility must be located in /usr/bin/</li> <li>the needed <code>bash</code> binary must be located in <code>PATH</code></li> </ul> <p>Which one you need, or whether you think which one is good, or bad, is up to you. There is no bulletproof portable way to specify an interpreter. It's a common misconception that it solves all problems. Period.</p>","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/basics/#the-standard-filedescriptors","title":"The standard filedescriptors","text":"<p>Once Initialized, every normal UNIX\u00ae-program has at least 3 open files:</p> <ul> <li>stdin: standard input</li> <li>stdout: standard output</li> <li>stderr: standard error output</li> </ul> <p>Usually, they're all connected to your terminal, stdin as input file (keyboard), stdout and stderr as output files (screen). When calling such a program, the invoking shell can change these filedescriptor connections away from the terminal to any other file (see redirection). Why two different output filedescriptors? It's convention to send error messages and warnings to stderr and only program output to stdout. This enables the user to decide if they want to see nothing, only the data, only the errors, or both - and where they want to see them.</p> <p>When you write a script:</p> <ul> <li>always read user-input from <code>stdin</code></li> <li>always write diagnostic/error/warning messages to <code>stderr</code></li> </ul> <p>To learn more about the standard filedescriptors, especially about redirection and piping, see:</p> <ul> <li>An illustrated redirection tutorial</li> </ul>","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/basics/#variable-names","title":"Variable names","text":"<p>It's good practice to use lowercase names for your variables, as shell and system-variable names are usually all in UPPERCASE. However, you should avoid naming your variables any of the following (incomplete list!):</p> <code>BASH</code> <code>BASH_ARGC</code> <code>BASH_ARGV</code> <code>BASH_LINENO</code> <code>BASH_SOURCE</code> <code>BASH_VERSINFO</code> <code>BASH_VERSION</code> <code>COLUMNS</code> <code>DIRSTACK</code> <code>DISPLAY</code> <code>EDITOR</code> <code>EUID</code> <code>GROUPS</code> <code>HISTFILE</code> <code>HISTFILESIZE</code> <code>HISTSIZE</code> <code>HOME</code> <code>HOSTNAME</code> <code>IFS</code> <code>LANG</code> <code>LANGUAGE</code> <code>LC_ALL</code> <code>LINES</code> <code>LOGNAME</code> <code>LS_COLORS</code> <code>MACHTYPE</code> <code>MAILCHECK</code> <code>OLDPWD</code> <code>OPTERR</code> <code>OPTIND</code> <code>OSTYPE</code> <code>PATH</code> <code>PIPESTATUS</code> <code>PPID</code> <code>PROMPT_COMMAND</code> <code>PS1</code> <code>PS2</code> <code>PS4</code> <code>PS3</code> <code>PWD</code> <code>SHELL</code> <code>SHELLOPTS</code> <code>SHLVL</code> <code>TERM</code> <code>UID</code> <code>USER</code> <code>USERNAME</code> <code>XAUTHORITY</code> <p>This list is incomplete. The safest way is to use all-lowercase variable names.</p>","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/basics/#exit-codes","title":"Exit codes","text":"<p>Every program you start terminates with an exit code and reports it to the operating system. This exit code can be utilized by Bash. You can show it, you can act on it, you can control script flow with it. The code is a number between 0 and 255. Values from 126 to 255 are reserved for use by the shell directly, or for special purposes, like reporting a termination by a signal:</p> <ul> <li>126: the requested command (file) was found, but can't be executed</li> <li>127: command (file) not found</li> <li>128: according to ABS it's used to report an invalid argument to the exit builtin, but I wasn't able to verify that in the source code of Bash (see code 255)</li> <li>128 + N: the shell was terminated by the signal N</li> <li>255: wrong argument to the exit builtin (see code 128)</li> </ul> <p>The lower codes 0 to 125 are not reserved and may be used for whatever the program likes to report. A value of 0 means successful termination, a value not 0 means unsuccessful termination. This behavior (== 0, != 0) is also what Bash reacts to in some flow control statements.</p> <p>An example of using the exit code of the program <code>grep</code> to check if a specific user is present in /etc/passwd:</p> <pre><code>if grep ^root /etc/passwd; then\n echo \"The user root was found\"\nelse\n echo \"The user root was not found\"\nfi\n</code></pre> <p>A common decision making command is \"<code>test</code>\" or its equivalent \"<code>[</code>\". But note that, when calling test with the name \"<code>[</code>\", the square brackets are not part of the shell syntax, the left bracket is the test command!</p> <pre><code>if [ \"$mystring\" = \"Hello world\" ]; then\n echo \"Yeah dude, you entered the right words...\"\nelse\n echo \"Eeeek - go away...\"\nfi\n</code></pre> <p>Read more about the test command</p> <p>A common exit code check method uses the \"<code>||</code>\" or \"<code>&amp;&amp;</code>\" operators. This lets you execute a command based on whether or not the previous command completed successfully:</p> <pre><code>grep ^root: /etc/passwd &gt;/dev/null || echo \"root was not found - check the pub at the corner.\"\nwhich vi &amp;&amp; echo \"Your favourite editor is installed.\"\n</code></pre> <p>Please, when your script exits on errors, provide a \"<code>FALSE</code>\" exit code, so others can check the script execution.</p>","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/basics/#comments","title":"Comments","text":"<p>In a larger, or complex script, it's wise to comment the code. Comments can help with debugging or tests. Comments start with the <code>#</code> character (hashmark) and continue to the end of the line:</p> <pre><code>#!/bin/bash\n# This is a small script to say something.\necho \"Be liberal in what you accept, and conservative in what you send\" # say something\n</code></pre> <p>The first thing was already explained, it's the so-called shebang, for the shell, only a comment. The second one is a comment from the beginning of the line, the third comment starts after a valid command. All three syntactically correct.</p>","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/basics/#block-commenting","title":"Block commenting","text":"<p>To temporarily disable complete blocks of code you would normally have to prefix every line of that block with a <code>#</code> (hashmark) to make it a comment. There's a little trick, using the pseudo command <code>:</code> (colon) and input redirection. The <code>:</code> does nothing, it's a pseudo command, so it does not care about standard input. In the following code example, you want to test mail and logging, but not dump the database, or execute a shutdown:</p> <pre><code>#!/bin/bash\n# Write info mails, do some tasks and bring down the system in a safe way\necho \"System halt requested\" | mail -s \"System halt\" netadmin@example.com\nlogger -t SYSHALT \"System halt requested\"\n\n##### The following \"code block\" is effectively ignored\n: &lt;&lt;\"SOMEWORD\"\n/etc/init.d/mydatabase clean_stop\nmydatabase_dump /var/db/db1 /mnt/fsrv0/backups/db1\nlogger -t SYSHALT \"System halt: pre-shutdown actions done, now shutting down the system\"\nshutdown -h NOW\nSOMEWORD\n##### The ignored codeblock ends here\n</code></pre> <p>What happened? The <code>:</code> pseudo command was given some input by redirection (a here-document) - the pseudo command didn't care about it, effectively, the entire block was ignored.</p> <p>The here-document-tag was quoted here to avoid substitutions in the \"commented\" text! Check redirection with here-documents for more</p>","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/basics/#variable-scope","title":"Variable scope","text":"<p>In Bash, the scope of user variables is generally global. That means, it does not matter whether a variable is set in the \"main program\" or in a \"function\", the variable is defined everywhere.</p> <p>Compare the following equivalent code snippets:</p> <pre><code>myvariable=test\necho $myvariable\n</code></pre> <pre><code>myfunction() {\n myvariable=test\n}\n\nmyfunction\necho $myvariable\n</code></pre> <p>In both cases, the variable <code>myvariable</code> is set and accessible from everywhere in that script, both in functions and in the \"main program\".</p> <p>Attention: When you set variables in a child process, for example a subshell, they will be set there, but you will never have access to them outside of that subshell. One way to create a subshell is the pipe. It's all mentioned in a small article about Bash in the processtree!</p>","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/basics/#local-variables","title":"Local variables","text":"<p>Bash provides ways to make a variable's scope local to a function:</p> <ul> <li>Using the <code>local</code> keyword, or</li> <li>Using <code>declare</code> (which will detect when it was called from within a function and make the variable(s) local).</li> </ul> <pre><code>myfunc() {\nlocal var=VALUE\n\n# alternative, only when used INSIDE a function\ndeclare var=VALUE\n\n...\n}\n</code></pre> <p>The local keyword (or declaring a variable using the <code>declare</code> command) tags a variable to be treated completely local and separate inside the function where it was declared:</p> <pre><code>foo=external\n\nprintvalue() {\nlocal foo=internal\n\necho $foo\n}\n\n\n# this will print \"external\"\necho $foo\n\n# this will print \"internal\"\nprintvalue\n\n# this will print - again - \"external\"\necho $foo\n</code></pre>","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/basics/#environment-variables","title":"Environment variables","text":"<p>The environment space is not directly related to the topic about scope, but it's worth mentioning.</p> <p>Every UNIX\u00ae process has a so-called environment. Other items, in addition to variables, are saved there, the so-called environment variables. When a child process is created (in Bash e.g. by simply executing another program, say <code>ls</code> to list files), the whole environment including the environment variables is copied to the new process. Reading that from the other side means: Only variables that are part of the environment are available in the child process.</p> <p>A variable can be tagged to be part of the environment using the <code>export</code> command:</p> <pre><code># create a new variable and set it:\n# -&gt; This is a normal shell variable, not an environment variable!\nmyvariable=\"Hello world.\"\n\n# make the variable visible to all child processes:\n# -&gt; Make it an environment variable: \"export\" it\nexport myvariable\n</code></pre> <p>Remember that the exported variable is a copy. There is no provision to \"copy it back to the parent.\" See the article about Bash in the process tree!</p> <ol> <li> <p>under specific circumstances, also by the shell itself\u00a0\u21a9</p> </li> </ol>","tags":["bash","shell","scripting","basics","learning","tutorial"]},{"location":"scripting/debuggingtips/","title":"Debugging a script","text":"<p>These few lines are not intended as a full-fledged debugging tutorial, but as hints and comments about debugging a Bash script.</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#use-a-unique-name-for-your-script","title":"Use a unique name for your script","text":"<p>Do not name your script <code>test</code>, for example! Why? <code>test</code> is the name of a UNIX\u00ae-command, and most likely built into your shell (it's a built-in in Bash) - so you won't be able to run a script with the name <code>test</code> in a normal way.</p> <p>Don't laugh! This is a classic mistake :-)</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#read-the-error-messages","title":"Read the error messages","text":"<p>Many people come into IRC and ask something like \"Why does my script fail? I get an error!\". And when you ask them what the error message is, they don't even know. Beautiful.</p> <p>Reading and interpreting error messages is 50% of your job as debugger! Error messages actually mean something. At the very least, they can give you hints as to where to start debugging. READ YOUR ERROR MESSAGES!</p> <p>You may ask yourself why is this mentioned as debugging tip? Well, you would be surprised how many shell users ignore the text of error messages! When I find some time, I'll paste 2 or 3 IRC log-snips here, just to show you that annoying fact.</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#use-a-good-editor","title":"Use a good editor","text":"<p>Your choice of editor is a matter of personal preference, but one with Bash syntax highlighting is highly recommended! Syntax highlighting helps you see (you guessed it) syntax errors, such as unclosed quotes and braces, typos, etc.</p> <p>From my personal experience, I can suggest <code>vim</code> or <code>GNU emacs</code>.</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#write-logfiles","title":"Write logfiles","text":"<p>For more complex scripts, it's useful to write to a log file, or to the system log. Nobody can debug your script without knowing what actually happened and what went wrong.</p> <p>An available syslog interface is <code>logger</code> (online manpage).</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#inject-debugging-code","title":"Inject debugging code","text":"<p>Insert echos everywhere you can, and print to <code>stderr</code>:</p> <pre><code>echo \"DEBUG: current i=$i\" &gt;&amp;2\n</code></pre> <p>If you read input from anywhere, such as a file or command substitution, print the debug output with literal quotes, to see leading and trailing spaces!</p> <pre><code>pid=$(&lt; fooservice.pid)\necho \"DEBUG: read from file: pid=\\\"$pid\\\"\" &gt;&amp;2\n</code></pre> <p>Bash's printf command has the <code>%q</code> format, which is handy for verifying whether strings are what they appear to be.</p> <pre><code>foo=$(&lt; inputfile)\nprintf \"DEBUG: foo is |%q|\\n\" \"$foo\" &gt;&amp;2\n# exposes whitespace (such as CRs, see below) and non-printing characters\n</code></pre>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#use-shell-debug-output","title":"Use shell debug output","text":"<p>There are two useful debug outputs for that task (both are written to <code>stderr</code>):</p> <ul> <li><code>set -v</code> mode (<code>set -o verbose</code>)<ul> <li>print commands to be executed to <code>stderr</code> as if they were read from input (script file or keyboard)</li> <li>print everything before any (substitution and expansion, ...) is applied</li> </ul> </li> <li><code>set -x</code> mode (<code>set -o xtrace</code>)<ul> <li>print everything as if it were executed, after substitution and expansion is applied</li> <li>indicate the depth-level of the subshell (by default by prefixing a <code>+</code> (plus) sign to the displayed command)</li> <li>indicate the recognized words after word splitting by marking them like <code>'x y'</code></li> <li>in shell version 4.1, this debug output can be printed to a configurable file descriptor, rather than sdtout by setting the BASH_XTRACEFD variable.</li> </ul> </li> </ul> <p>Hint: These modes can be entered when calling Bash:</p> <ul> <li>from commandline: <code>bash -vx ./myscript</code></li> <li>from shebang (OS dependant): <code>#!/bin/bash -vx</code></li> </ul>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#simple-example-of-how-to-interpret-xtrace-output","title":"Simple example of how to interpret xtrace output","text":"<p>Here's a simple command (a string comparison using the classic test command) executed while in <code>set -x</code> mode:</p> <pre><code>set -x\nfoo=\"bar baz\"\n[ $foo = test ]\n</code></pre> <p>That fails. Why? Let's see the <code>xtrace</code> output:</p> <pre><code>+ '[' bar baz = test ']'\n</code></pre> <p>And now you see that it's (\"bar\" and \"baz\") recognized as two separate words (which you would have realized if you READ THE ERROR MESSAGES ;) ). Let's check it...</p> <pre><code># next try\n[ \"$foo\" = test ]\n</code></pre> <p><code>xtrace</code> now gives</p> <pre><code>+ '[' 'bar baz' = test ']'\n ^ ^\n word markers!\n</code></pre>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#making-xtrace-more-useful","title":"Making xtrace more useful","text":"<p>(by AnMaster)</p> <p><code>xtrace</code> output would be more useful if it contained source file and line number. Add this assignment PS4 at the beginning of your script to enable the inclusion of that information:</p> <pre><code>export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'\n</code></pre> <p>Be sure to use single quotes here!</p> <p>The output would look like this when you trace code outside a function:</p> <pre><code>+(somefile.bash:412): echo 'Hello world'\n</code></pre> <p>...and like this when you trace code inside a function:</p> <pre><code>+(somefile.bash:412): myfunc(): echo 'Hello world'\n</code></pre> <p>That helps a lot when the script is long, or when the main script sources many other files.</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#set-flag-variables-with-descriptive-words","title":"Set flag variables with descriptive words","text":"<p>If you test variables that flag the state of options, such as with <code>if [[ -n $option ]];</code>, consider using descriptive words rather than short codes, such as 0, 1, Y, N, because xtrace will show <code>[[ -n word ]]</code> rather than <code>[[ -n 1 ]]</code> when the option is set.</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#debugging-commands-depending-on-a-set-variable","title":"Debugging commands depending on a set variable","text":"<p>For general debugging purposes you can also define a function and a variable to use:</p> <pre><code>debugme() {\n [[ $script_debug = 1 ]] &amp;&amp; \"$@\" || :\n # be sure to append || : or || true here or use return 0, since the return code\n # of this function should always be 0 to not influence anything else with an unwanted\n # \"false\" return code (for example the script's exit code if this function is used\n # as the very last command in the script)\n}\n</code></pre> <p>This function does nothing when <code>script_debug</code> is unset or empty, but it executes the given parameters as commands when <code>script_debug</code> is set. Use it like this:</p> <pre><code>script_debug=1\n# to turn it off, set script_debug=0\n\ndebugme logger \"Sorting the database\"\ndatabase_sort\ndebugme logger \"Finished sorting the database, exit code $?\"\n</code></pre> <p>Of course this can be used to execute something other than echo during debugging:</p> <pre><code>debugme set -x\n# ... some code ...\ndebugme set +x\n</code></pre>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#dry-run-stdin-driven-commands","title":"Dry-run STDIN driven commands","text":"<p>Imagine you have a script that runs FTP commands using the standard FTP client:</p> <pre><code>ftp user@host &lt;&lt;FTP\ncd /data\nget current.log\ndele current.log\nFTP\n</code></pre> <p>A method to dry-run this with debug output is:</p> <pre><code>if [[ $DRY_RUN = yes ]]; then\n sed 's/^/DRY_RUN FTP: /'\nelse\n ftp user@host\nfi &lt;&lt;FTP\ncd /data\nget current.log\ndele current.log\nFTP\n</code></pre> <p>This can be wrapped in a shell function for more readable code.</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#common-error-messages","title":"Common error messages","text":"","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#unexpected-end-of-file","title":"Unexpected end of file","text":"<pre><code>script.sh: line 100: syntax error: unexpected end of file\n</code></pre> <p>Usually indicates exactly what it says: An unexpected end of file. It's unexpected because Bash waits for the closing of a compound command:</p> <ul> <li>did you close your <code>do</code> with a <code>done</code>?</li> <li>did you close your <code>if</code> with a <code>fi</code>?</li> <li>did you close your <code>case</code> with a <code>esac</code>?</li> <li>did you close your <code>{</code> with a <code>}</code>?</li> <li>did you close your <code>(</code> with a <code>)</code>?</li> </ul> <p>Note: It seems that here-documents (tested on versions <code>1.14.7</code>, <code>2.05b</code>, <code>3.1.17</code> and <code>4.0</code>) are correctly terminated when there is an EOF before the end-of-here-document tag (see redirection). The reason is unknown, but it seems to be deliberate. Bash 4.0 added an extra message for this: <code>warning: here-document at line &lt;N&gt; delimited by end-of-file (wanted `&lt;MARKER&gt;')</code></p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#unexpected-end-of-file-while-looking-for-matching","title":"Unexpected end of file while looking for matching ...","text":"<pre><code>script.sh: line 50: unexpected EOF while looking for matching `\"'\nscript.sh: line 100: syntax error: unexpected end of file\n</code></pre> <p>This one indicates the double-quote opened in line 50 does not have a matching closing quote.</p> <p>These unmatched errors occur with:</p> <ul> <li>double-quote pairs</li> <li>single-quote pairs (also <code>$'string'</code>!)</li> <li>missing a closing <code>}</code> with parameter expansion syntax</li> </ul>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#too-many-arguments","title":"Too many arguments","text":"<pre><code>bash: test: too many arguments\n</code></pre> <p>You most likely forgot to quote a variable expansion somewhere. See the example for <code>xtrace</code> output from above. External commands may display such an error message though in our example, it was the internal test-command that yielded the error.</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#event-not-found","title":"!\": event not found","text":"<pre><code>$ echo \"Hello world!\"\nbash: !\": event not found\n</code></pre> <p>This is not an error per se. It happens in interactive shells, when the C-Shell-styled history expansion (\"<code>!searchword</code>\") is enabled. This is the default. Disable it like this:</p> <pre><code>set +H\n# or\nset +o histexpand\n</code></pre>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#syntax-error-near-unexpected-token","title":"syntax error near unexpected token `(\\'","text":"<p>When this happens during a script function definition or on the commandline, e.g.</p> <pre><code>$ foo () { echo \"Hello world\"; }\nbash: syntax error near unexpected token `('\n</code></pre> <p>you most likely have an alias defined with the same name as the function (here: <code>foo</code>). Alias expansion happens before the real language interpretion, thus the alias is expanded and makes your function definition invalid.</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#the-crlf-issue","title":"The CRLF issue","text":"","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#what-is-the-crlf-issue","title":"What is the CRLF issue?","text":"<p>There's a big difference in the way that UNIX\u00ae and Microsoft\u00ae (and possibly others) handle the line endings of plain text files. The difference lies in the use of the CR (Carriage Return) and LF (Line Feed) characters.</p> <ul> <li>MSDOS uses: <code>\\r\\n</code> (ASCII <code>CR</code> #13 <code>^M</code>, ASCII LF #10)</li> <li>UNIX\u00ae uses: <code>\\n</code> (ASCII <code>LF</code> #10)</li> </ul> <p>Keep in mind your script is a plain text file, and the <code>CR</code> character means nothing special to UNIX\u00ae - it is treated like any other character. If it's printed to your terminal, a carriage return will effectively place the cursor at the beginning of the current line. This can cause much confusion and many headaches, since lines containing CRs are not what they appear to be when printed. In summary, CRs are a pain.</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#how-did-a-cr-end-up-in-my-file","title":"How did a CR end up in my file?","text":"<p>Some possible sources of CRs:</p> <ul> <li>a DOS/Windows text editor</li> <li>a UNIX\u00ae text editor that is \"too smart\" when determining the file content type (and thinks \"it's a DOS text file\")</li> <li>a direct copy and paste from certain webpages (some pastebins are known for this)</li> </ul>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#why-do-crs-hurt","title":"Why do CRs hurt?","text":"<p>CRs can be a nuisance in various ways. They are especially bad when present in the shebang/interpreter specified with <code>#!</code> in the very first line of a script. Consider the following script, written with a Windows\u00ae text editor (<code>^M</code> is a symbolic representation of the <code>CR</code> carriage return character!):</p> <pre><code>#!/bin/bash^M\n^M\necho \"Hello world\"^M\n...\n</code></pre> <p>Here's what happens because of the <code>#!/bin/bash^M</code> in our shebang:</p> <ul> <li>the file <code>/bin/bash^M</code> doesn't exist (hopefully)</li> <li>So Bash prints an error message which (depending on the terminal, the Bash version, or custom patches!) may or may not expose the problem.</li> <li>the script can't be executed</li> </ul> <p>The error message can vary. If you're lucky, you'll get:</p> <pre><code>bash: ./testing.sh: /bin/bash^M: bad interpreter: No such file or directory\n</code></pre> <p>which alerts you to the CR. But you may also get the following:</p> <pre><code>: bad interpreter: No such file or directory\n</code></pre> <p>Why? Because when printed literally, the <code>^M</code> makes the cursor go back to the beginning of the line. The whole error message is printed, but you see only part of it!</p> <p>warning</p> <p>It's easy to imagine the <code>^M</code> is bad in other places too. If you get weird and illogical messages from your script, rule out the possibility that<code>^M</code> is involved. Find and eliminate it!</p>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#how-can-i-find-and-eliminate-them","title":"How can I find and eliminate them?","text":"<p>To display CRs (these are only a few examples)</p> <ul> <li>in VI/VIM: <code>:set list</code></li> <li>with <code>cat(1)</code>: <code>cat -v FILE</code></li> </ul> <p>To eliminate them (only a few examples)</p> <ul> <li>blindly with <code>tr(1)</code>: <code>tr -d '\\r' &lt;FILE &gt;FILE.new</code></li> <li>controlled with <code>recode(1)</code>: <code>recode MSDOS..latin1 FILE</code></li> <li>controlled with <code>dos2unix(1)</code>: <code>dos2unix FILE</code></li> </ul>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/debuggingtips/#see-also","title":"See also","text":"<ul> <li>the set builtin command (for <code>-v</code> and <code>-x</code>)</li> </ul> <p>FIXME</p> <p>tbd.</p> <ul> <li>DEBUG trap</li> <li>BASH Debugger http://bashdb.sourceforge.net/</li> </ul>","tags":["bash","shell","scripting","bug","debug","debugging"]},{"location":"scripting/newbie_traps/","title":"Beginner Mistakes","text":"<p>Here are some typical traps:</p>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#script-execution","title":"Script execution","text":"","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#your-perfect-bash-script-executes-with-syntax-errors","title":"Your perfect Bash script executes with syntax errors","text":"<p>If you write Bash scripts with Bash specific syntax and features, run them with Bash, and run them with Bash in native mode.</p> <p>Wrong:</p> <ul> <li>no shebang<ul> <li>the interpreter used depends on the OS implementation and current shell</li> <li>can be run by calling bash with the script name as an argument, e.g. <code>bash myscript</code></li> </ul> </li> <li><code>#!/bin/sh</code> shebang<ul> <li>depends on what <code>/bin/sh</code> actually is, for a Bash it means compatiblity mode, not native mode</li> </ul> </li> </ul> <p>See also:</p> <ul> <li>Bash startup mode: SH mode</li> <li>Bash run mode: POSIX mode</li> </ul>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#your-script-named-test-doesnt-execute","title":"Your script named \"test\" doesn't execute","text":"<p>Give it another name. The executable <code>test</code> already exists.</p> <p>In Bash it's a builtin. With other shells, it might be an executable file. Either way, it's bad name choice!</p> <p>Workaround: You can call it using the pathname:</p> <pre><code>/home/user/bin/test\n</code></pre>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#globbing","title":"Globbing","text":"","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#brace-expansion-is-not-globbing","title":"Brace expansion is not globbing","text":"<p>The following command line is not related to globbing (filename expansion):</p> <pre><code># YOU EXPECT\n# -i1.vob -i2.vob -i3.vob ....\n\necho -i{*.vob,}\n\n# YOU GET\n# -i*.vob -i\n</code></pre> <p>Why? The brace expansion is simple text substitution. All possible text formed by the prefix, the postfix and the braces themselves are generated. In the example, these are only two: <code>-i*.vob</code> and <code>-i</code>. The filename expansion happens after that, so there is a chance that <code>-i*.vob</code> is expanded to a filename - if you have files like <code>-ihello.vob</code>. But it definitely doesn't do what you expected.</p> <p>Please see:</p> <ul> <li>brace</li> </ul>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#test-command","title":"Test-command","text":"<ul> <li><code>if [ $foo ] ...</code></li> <li><code>if [-d $dir] ...</code></li> <li>...</li> </ul> <p>Please see:</p> <ul> <li>The classic test command - pitfalls</li> </ul>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#variables","title":"Variables","text":"","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#setting-variables","title":"Setting variables","text":"","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#the-dollar-sign","title":"The Dollar-Sign","text":"<p>There is no <code>$</code> (dollar-sign) when you reference the name of a variable! Bash is not PHP!</p> <pre><code># THIS IS WRONG!\n$myvar=\"Hello world!\"\n</code></pre> <p>A variable name preceeded with a dollar-sign always means that the variable gets expanded. In the example above, it might expand to nothing (because it wasn't set), effectively resulting in...</p> <pre><code>=\"Hello world!\"\n</code></pre> <p>...which definitely is wrong!</p> <p>When you need the name of a variable, you write only the name, for example</p> <ul> <li>(as shown above) to set variables: <code>picture=/usr/share/images/foo.png</code></li> <li>to name variables to be used by the <code>read</code> builtin command: <code>read picture</code></li> <li>to name variables to be unset: <code>unset picture</code></li> </ul> <p>When you need the content of a variable, you prefix its name with a dollar-sign, like</p> <pre><code>echo \"The used picture is: $picture\"\n</code></pre>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#whitespace","title":"Whitespace","text":"<p>Putting spaces on either or both sides of the equal-sign (<code>=</code>) when assigning a value to a variable will fail.</p> <pre><code># INCORRECT 1\nexample = Hello\n\n# INCORRECT 2\nexample= Hello\n\n# INCORRECT 3\nexample =Hello\n</code></pre> <p>The only valid form is no spaces between the variable name and assigned value:</p> <pre><code># CORRECT 1\nexample=Hello\n\n# CORRECT 2\nexample=\" Hello\"\n</code></pre>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#expanding-using-variables","title":"Expanding (using) variables","text":"<p>A typical beginner's trap is quoting.</p> <p>As noted above, when you want to expand a variable i.e. \\\"get the content\\\", the variable name needs to be prefixed with a dollar-sign. But, since Bash knows various ways to quote and does word-splitting, the result isn't always the same.</p> <p>Let's define an example variable containing text with spaces:</p> <pre><code>example=\"Hello world\"\n</code></pre> Used form result number of words <code>$example</code> <code>Hello world</code> 2 <code>\"$example\"</code> <code>Hello world</code> 1 <code>\\$example</code> <code>$example</code> 1 <code>'$example'</code> <code>$example</code> 1 <p>If you use parameter expansion, you must use the name (<code>PATH</code>) of the referenced variables/parameters. i.e. not (<code>$PATH</code>):</p> <pre><code># WRONG!\necho \"The first character of PATH is ${$PATH:0:1}\"\n\n# CORRECT\necho \"The first character of PATH is ${PATH:0:1}\"\n</code></pre> <p>Note that if you are using variables in arithmetic expressions, then the bare name is allowed:</p> <pre><code>((a=$a+7)) # Add 7 to a\n((a = a + 7)) # Add 7 to a. Identical to the previous command.\n((a += 7)) # Add 7 to a. Identical to the previous command.\n\na=$((a+7)) # POSIX-compatible version of previous code.\n</code></pre> <p>Please see:</p> <ul> <li>words</li> <li>quoting</li> <li>wordsplit</li> <li>pe</li> </ul>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#exporting","title":"Exporting","text":"<p>Exporting a variable means giving newly created (child-)processes a copy of that variable. It does not copy a variable created in a child process back to the parent process. The following example does not work, since the variable <code>hello</code> is set in a child process (the process you execute to start that script <code>./script.sh</code>):</p> <pre><code>$ cat script.sh\nexport hello=world\n\n$ ./script.sh\n$ echo $hello\n$\n</code></pre> <p>Exporting is one-way. The direction is from parent process to child process, not the reverse. The above example will work, when you don't execute the script, but include (\\\"source\\\") it:</p> <pre><code>$ source ./script.sh\n$ echo $hello\nworld\n$\n</code></pre> <p>In this case, the export command is of no use.</p> <p>Please see:</p> <ul> <li>processtree</li> </ul>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#exit-codes","title":"Exit codes","text":"","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#reacting-to-exit-codes","title":"Reacting to exit codes","text":"<p>If you just want to react to an exit code, regardless of its specific value, you don't need to use <code>$?</code> in a test command like this:</p> <pre><code>grep ^root: /etc/passwd &gt;/dev/null 2&gt;&amp;1\n\nif [ $? -ne 0 ]; then\n echo \"root was not found - check the pub at the corner\"\nfi\n</code></pre> <p>This can be simplified to:</p> <pre><code>if ! grep ^root: /etc/passwd &gt;/dev/null 2&gt;&amp;1; then\n echo \"root was not found - check the pub at the corner\"\nfi\n</code></pre> <p>Or, simpler yet:</p> <pre><code>grep ^root: /etc/passwd &gt;/dev/null 2&gt;&amp;1 || echo \"root was not found - check the pub at the corner\"\n</code></pre> <p>If you need the specific value of <code>$?</code>, there's no other choice. But if you need only a \\\"true/false\\\" exit indication, there's no need for <code>$?</code>.</p> <p>See also:</p> <ul> <li>Exit codes</li> </ul>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/newbie_traps/#output-vs-return-value","title":"Output vs. Return Value","text":"<p>It's important to remember the different ways to run a child command, and whether you want the output, the return value, or neither.</p> <p>When you want to run a command (or a pipeline) and save (or print) the output, whether as a string or an array, you use Bash's <code>$(command)</code> syntax:</p> <pre><code>$(ls -l /tmp)\nnewvariable=$(printf \"foo\")\n</code></pre> <p>When you want to use the return value of a command, just use the command, or add ( ) to run a command or pipeline in a subshell:</p> <pre><code>if grep someuser /etc/passwd ; then\n # do something\nfi\n\nif ( w | grep someuser | grep sqlplus ) ; then\n # someuser is logged in and running sqlplus\nfi\n</code></pre> <p>Make sure you\\'re using the form you intended:</p> <pre><code># WRONG!\nif $(grep ERROR /var/log/messages) ; then\n # send alerts\nfi\n</code></pre> <p>Please see:</p> <ul> <li>intro</li> <li>cmdsubst</li> <li>grouping_subshell</li> </ul>","tags":["bash","shell","scripting","pitfalls","traps","beginners"]},{"location":"scripting/nonportable/","title":"Portability talk","text":"<p>The script programming language of BASH is based on the Bourne Shell syntax, with some extensions and derivations.</p> <p>If scripts need to be portable, some of the BASH-specific syntax elements should be avoided. Others should be avoided for all scripts, e.g. if there is a corresponding POSIX\u00ae-compatible syntax (see obsolete).</p> <p>Some syntax elements have a BASH-specific, and a portable<sup>1</sup>) pendant. In these cases the portable syntax should be preferred.</p> construct portable equivalent Description Portability <code>source FILE</code> <code>. FILE</code> include a script file Bourne shell (bash, ksh, POSIX\u00ae, zsh, \u2026) <code>declare</code> keyword <code>typeset</code> keyword define local variables (or variables with special attributes) ksh, zsh, \u2026, not POSIX! <code>command &lt;&lt;&lt; WORD</code> <code>command &lt;&lt;MARKER</code>\\n<code>WORD</code>\\n<code>MARKER</code> a here-string, a special form of the here-document, avoid it in portable scripts! POSIX\u00ae <code>export VAR=VALUE</code> <code>VAR=VALUE</code>\\n<code>export VAR</code> Though POSIX\u00ae allows it, some shells don't want the assignment and the exporting in one command POSIX\u00ae, zsh, ksh, \u2026 <code>(( MATH ))</code> <code>: $(( MATH ))</code> POSIX\u00ae does't define an arithmetic compund command, many shells don't know it. Using the pseudo-command <code>:</code> and the arithmetic expansion <code>$(( ))</code> is a kind of workaround here. Attention: Not all shell support assignment like <code>$(( a = 1 + 1 ))</code>! Also see below for a probably more portable solution. all POSIX\u00ae compatible shells <code>[[ EXPRESSION ]]</code> <code>[ EXPRESSION ]</code>\\nor\\n<code>test EXPRESSION</code> The Bashish test keyword is reserved by POSIX\u00ae, but not defined. Use the old fashioned way with the <code>test</code> command. See [[web/20230315170826/https://wiki.bash-hackers.org/commands/classictest]] POSIX\u00ae and others <code>COMMAND &lt; &lt;( \u2026INPUTCOMMANDS\u2026 )</code> <code>INPUTCOMMANDS &gt; TEMPFILE</code>\\n<code>COMMAND &lt; TEMPFILE</code> Process substitution (here used with redirection); use the old fashioned way (tempfiles) POSIX\u00ae and others <code>((echo X);(echo Y))</code> <code>( (echo X); (echo Y) )</code> Nested subshells (separate the inner <code>()</code> from the outer <code>()</code> by spaces, to not confuse the shell regarding arithmetic control operators) POSIX\u00ae and others","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#portability-rationale","title":"Portability rationale","text":"<p>Here is some assorted portability information. Take it as a small guide to make your scripts a bit more portable. It's not complete (it never will be!) and it's not very detailed (e.g. you won't find information about how which shell technically forks off which subshell). It's just an assorted small set of portability guidelines. -Thebonsai</p> <p>FIXME</p> <p>UNIX shell gurus out there, please be patient with a newbie like me and give comments and hints instead of flames.</p>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#environment-exported-variables","title":"Environment (exported) variables","text":"<p>When a new value is assigned to an existing environment variable, there are two possibilities:</p> <p>The new value is seen by subsequent programs</p> <ul> <li>without any special action (e.g. Bash)</li> <li>only after an explicit export with <code>export VARIABLE</code> (e.g. Sun's <code>/bin/sh</code>)</li> </ul> <p>Since an extra <code>export</code> doesn't hurt, the safest and most portable way is to always (re-)export a changed variable if you want it to be seen by subsequent processes.</p>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#arithmetics","title":"Arithmetics","text":"<p>Bash has a special compound command to do arithmetic without expansion. However, POSIX has no such command. In the table at the top, there's the <code>: $((MATH))</code> construct mentioned as possible alternative. Regarding the exit code, a 100% equivalent construct would be:</p> <pre><code># Bash (or others) compound command\nif ((MATH)); then\n...\n\n# portable equivalent command\nif [ \"$((MATH))\" -ne 0 ]; then\n...\n</code></pre> <p>Quotes around the arithmetic expansion <code>$((MATH))</code> should not be necessary as per POSIX, but Bash and AT&amp;T-KSH perform word-splitting on aritrhmetic expansions, so the most portable is with quotes.</p>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#echo-command","title":"echo command","text":"<p>The overall problem with <code>echo</code> is, that there are 2 (maybe more) mainstream flavours around. The only case where you may safely use an <code>echo</code> on all systems is: Echoing non-variable arguments that don't start with a <code>-</code> (dash) and don't contain a <code>\\</code> (backslash).</p> <p>Why? (list of known behaviours)</p> <ul> <li>may or may not automatically interpret backslash escpape codes in the strings</li> <li>may or may not automatically interpret switches (like <code>-n</code>)</li> <li>may or may not ignore \"end of options\" tag (<code>--</code>)</li> <li><code>echo -n</code> and <code>echo -e</code> are neither portable nor standard (even within the same shell, depending on the version or environment variables or the build options, especially KSH93 and Bash)</li> </ul> <p>For these, and possibly other, reasons, POSIX (SUS) standardized the existance of the <code>printf</code> command.</p>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#parameter-expansions","title":"Parameter expansions","text":"<ul> <li><code>${var:x:x}</code> is KSH93/Bash specific</li> <li><code>${var/../..}</code> and <code>${var//../..}</code> are KSH93/Bash specific</li> <li><code>var=$*</code> and <code>var=$@</code> are not handled the same in all shells if the first char of IFS is not \" \" (space). <code>var=\"$*\"</code> should work (except the Bourne shell always joins the expansions with space)</li> </ul>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#special-variables","title":"Special variables","text":"","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#pwd","title":"PWD","text":"<p>PWD is POSIX but not Bourne. Most shells are not POSIX in that they don't ignore the value of the <code>PWD</code> environment variable. Workaround to fix the value of <code>PWD</code> at the start of your script:</p> <pre><code>pwd -P &gt; dev/null\n</code></pre>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#random","title":"RANDOM","text":"<p>RANDOM is Bash/KSH/ZSH specific variable that will give you a random number up to 32767 (2^15-1). Among many other available external options, you can use awk to generate a random number. There are multiple implementations of awk and which version your system uses will depend. Most modern systems will call 'gawk' (i.e. GNU awk) or 'nawk'. 'oawk' (i.e. Original/Old awk) does not have the rand() or srand() functions, so is best avoided.</p> <pre><code># 'gawk' can produce random numbers using srand(). In this example, 10 integers between 1 and 500:\nrandpm=$(gawk -v min=1 -v max=500 -v nNum=10 'BEGIN { srand(systime() + PROCINFO[\"pid\"]); for (i = 0; i &lt; nNum; ++i) {print int(min + rand() * (max - min)} }')\n\n# 'nawk' and 'mawk' does the same, but needs a seed to be provided for its rand() function. In this example we use $(date)\nrandpm=$(mawk -v min=1 -v max=500 -v nNum=10 -v seed=\"$(date +%Y%M%d%H%M%S)\" 'BEGIN { srand(seed); for (i = 0; i &lt; nNum; ++i) {print int(min + rand() * (max - min)} }')\n</code></pre> <p>Yes, I'm not an <code>awk</code> expert, so please correct it, rather than complaining about possible stupid code!</p> <pre><code># Well, seeing how this //is// BASH-hackers.org I kinda missed the bash way of doing the above ;-)\n# print a number between 0 and 500 :-)\n printf $(( 500 * RANDOM / 32767 ))\n\n# Or print 30 random numbers between 0 and 10 ;)\n X=0; while (( X++ &lt; 30 )); do echo $(( 10 * RANDOM / 32767 )); done\n</code></pre>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#seconds","title":"SECONDS","text":"<p>SECONDS is KSH/ZSH/Bash specific. Avoid it. Find another method.</p>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#check-for-a-command-in-path","title":"Check for a command in PATH","text":"<p>The PATH variable is a colon-delimited list of directory names, so it's basically possible to run a loop and check every <code>PATH</code> component for the command you're looking for and for executability.</p> <p>However, this method doesn't look nice. There are other ways of doing this, using commands that are not directly related to this task.</p>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#hash","title":"hash","text":"<p>The <code>hash</code> command is used to make the shell store the full pathname of a command in a lookup-table (to avoid re-scanning the <code>PATH</code> on every command execution attempt). Since it has to do a <code>PATH</code> search, it can be used for this check.</p> <p>For example, to check if the command <code>ls</code> is available in a location accessible by <code>PATH</code>:</p> <pre><code>if hash ls &gt;/dev/null 2&gt;&amp;1; then\n echo \"ls is available\"\nfi\n</code></pre> <p>Somewhat of a mass-check:</p> <pre><code>for name in ls grep sed awk; do\n if ! hash \"$name\" &gt;/dev/null 2&gt;&amp;1; then\n echo \"FAIL: Missing command '$name'\"\n exit 1\n fi\ndone\n</code></pre> <p>Here (bash 3), <code>hash</code> also respects builtin commands. I don't know if this works everywhere, but it seems logical.</p>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/nonportable/#command","title":"command","text":"<p>The <code>command</code> command is used to explicitly call an external command, rather than a builtin with the same name. For exactly this reason, it has to do a <code>PATH</code> search, and can be used for this check.</p> <p>For example, to check if the command <code>sed</code> is available in a location accessible by <code>PATH</code>:</p> <pre><code>if command -v sed &gt;/dev/null 2&gt;&amp;1; then\n echo \"sed is available\"\nfi\n</code></pre> <ol> <li> <p>\"portable\" doesn't necessarily mean it's POSIX, it can also mean it's \"widely used and accepted\", and thus maybe more portable than POSIX(r\u00a0\u21a9</p> </li> </ol>","tags":["bash","shell","scripting","portability","POSIX","portable"]},{"location":"scripting/obsolete/","title":"Obsolete and deprecated syntax","text":"<p>This (incomplete) page describes some syntax and commands considered obsolete by some measure. A thorough discussion of the rationale is beyond the scope of this page. See the portability page for a discussion on portability issues.</p>","tags":["bash","shell","scripting","obsolete","deprecated","outdated"]},{"location":"scripting/obsolete/#tolerated-but-few-ligitimate-uses","title":"Tolerated but few ligitimate uses","text":"<p>This first table lists syntax that is tolerated by Bash but has few if any legitimate uses. These features exist mostly for Bourne, csh, or some other backward compatibility with obsolete shells, or were Bash-specific features considered failed experiments and deprecated or replaced with a better alternative. These should be irrelevant to most everyone except maybe code golfers. New scripts should never use them. None of the items on this list are specified by the most current version of POSIX, and some may be incompatible with POSIX.</p> Syntax Replacement Description <code>&amp;&gt;FILE</code> and <code>&gt;&amp;FILE</code> <code>&gt;FILE 2&gt;&amp;1</code> This redirection syntax is short for <code>&gt;FILE 2&gt;&amp;1</code> and originates in the C Shell. The latter form is especially uncommon and should never be used, and the explicit form using separate redirections is preferred over both. These shortcuts contribute to confusion about the copy descriptor because the syntax is unclear. They also introduce parsing ambiguity, and conflict with POSIX. Shells without this feature treat <code>cmd1 &amp;&gt;file cmd2</code> as: \"background <code>cmd1</code> and then execute <code>cmd2</code> with its stdout redirected to <code>file</code>\", which is the correct interpretation of this expression. See: redirection <pre>$ { bash; dash &lt;/dev/fd/0; } &lt;&lt;&lt;'echo foo&gt;/dev/null&amp;&gt;/dev/fd/2 echo bar'foo echo barbar</pre> <code>$[EXPRESSION]</code> <code>$((EXPRESSION))</code> This undocumented syntax is completely replaced by the POSIX-conforming arithmetic expansion <code>$((EXPRESSION))</code>. It is unimplemented almost everywhere except Bash and Zsh. See arithmetic expansion. Some discussion. <code>COMMAND|&amp; COMMAND</code> <code>COMMAND 2&gt;&amp;1| COMMAND</code> This is an alternate pipeline operator derived from Zsh. Officially, it is not considered deprecated by Bash, but I highly discourage it. It conflicts with the list operator used for coprocess creation in most Korn shells. It also has confusing behavior. The stdout is redirected first like an ordinary pipe, while the stderr is actually redirected last \u2013 after other redirects preceding the pipe operator. Overall, it's pointless syntax bloat. Use an explicit redirect instead. <code>function NAME() COMPOUND-CMD</code> <code>NAME() COMPOUND-CMD</code> or <code>function NAME { CMDS; }</code> This is an amalgamation between the Korn and POSIX style function definitions - using both the <code>function</code> keyword and parentheses. It has no useful purpose and no historical basis or reason to exist. It is not specified by POSIX. It is accepted by Bash, mksh, zsh, and perhaps some other Korn shells, where it is treated as identical to the POSIX-style function. It is not accepted by AT&amp;T ksh. It should never be used. See the next table for the <code>function</code> keyword. Bash doesn't have this feature documented as expressly deprecated. <code>for x; { ...;}</code> <code>do</code>, <code>done</code>, <code>in</code>, <code>esac</code>, etc. This undocumented syntax replaces the <code>do</code> and <code>done</code> reserved words with braces. Many Korn shells support various permutations on this syntax for certain compound commands like <code>for</code>, <code>case</code>, and <code>while</code>. Which ones and certain details like whether a newline or semicolon are required vary. Only <code>for</code> works in Bash. Needless to say, don't use it.","tags":["bash","shell","scripting","obsolete","deprecated","outdated"]},{"location":"scripting/obsolete/#syntax-superseded-by-superior-alternatives","title":"Syntax superseded by superior alternatives","text":"<p>This table lists syntax that is specified by POSIX (unless otherwise specified below), but has been superseded by superior alternatives (either in POSIX, Bash, or both), or is highly discouraged for other reasons such as encouraging bad practices or dangerous code. Those that are specified by POSIX may be badly designed and unchangeable for historical reasons.</p> Syntax Replacement Description Unquoted expansions, wordsplitting, and Pathname expansion (globbing) Proper quoting, Ksh/Bash-style arrays, The \"$@\" expansion, the read builtin command Quoting errors are a broad category of common mistakes brought about by a few unintuitive features carried over from the Bourne shell due to complaints of broken scripts and changes in previously documented behavior. Most of the important expansions are performed at the same time from left to right. However, a few expansions, most notably word-splitting and globbing, and in shells other than Bash, brace expansion, are performed on the results of previous expansions, by default, unless they are quoted. This means that the act of expanding an unquoted variable in an ordinary argument context, depending on the value of the variable, can yield different results depending on possibly uncontrolled side-effects like the value of <code>IFS</code>, and the names of files in the current working directory. You can't get globbing without word-splitting, or vice versa (without <code>set -f</code>). You can't store a command or character-delimited list in a variable and safely evaluate it with unquoted expansion. If possible, always choose a shell that supports Korn shell arrays such as Bash. They are a vital but non-standard feature for writing clean, safe scripts. Well-written scripts don't use word-splitting. A few exceptions are listed on the word splitting page. A significant proportion of the issues on the famous Pitfalls list fall under this category. See also: Don't read lines with for! <code>COMMANDS</code> <code>$(COMMANDS)</code> his is the older Bourne-compatible form of the command substitution. Both the <code>`COMMANDS`</code> and <code>$(COMMANDS)</code> syntaxes are specified by POSIX, but the latter is [greatly]{.underline} preferred, though the former is unfortunately still very prevalent in scripts. New-style command substitutions are widely implemented by every modern shell (and then some). The only reason for using backticks is for compatibility with a real Bourne shell (like Heirloom). Backtick command substitutions require special escaping when nested, and examples found in the wild are improperly quoted more often than not. See: Why is $(...) preferred over <code>...</code> (backticks)?. <code>[ EXPRESSION ]</code> and <code>test EXPRESSION</code> <code>[[ EXPRESSION ]]</code> <code>test</code> and <code>[</code> are the Bourne/POSIX commands for evaluating test expressions (they are almost identical, and <code>[</code> is somewhat more common). The expressions consist of regular arguments, unlike the Ksh/Bash <code>[[</code> command. While the issue is analogous to <code>let</code> vs <code>((</code>, the advantages of <code>[[</code> vs <code>[</code> are even more important because the arguments/expansions aren't just concatenated into one expression. With the classic <code>[</code> command, the number of arguments is significant. If at all possible, use the conditional expression (\"new test command\") <code>[[ EXPRESSION ]]</code>. Unless there is a need for POSIX compatibility, there are only a few reasons to use <code>[</code>. <code>[[</code> is one of the most portable and consistent non-POSIX ksh extensions available. See: conditional_expression and What is the difference between test, [ and [[ ? <code>set -e</code>, <code>set -o errexit</code> and the <code>ERR</code> trap proper control flow and error handling <code>set -e</code> causes untested non-zero exit statuses to be fatal. It is a debugging feature intended for use only during development and should not be used in production code, especially init scripts and other high-availability scripts. Do not be tempted to think of this as \"error handling\"; it's not, it's just a way to find the place you've forgotten to put error handling.Think of it as akin to <code>use strict</code> in Perl or <code>throws</code> in C++: tough love that makes you write better code. Many guides recommend avoiding it entirely because of the apparently-complex rules for when non-zero statuses cause the script to abort. Conversely, large software projects with experienced coders may recommend or even mandate its use.Because it provides no notification of the location of the error, it's more useful combined with <code>set -x</code> or the <code>DEBUG</code> trap and other Bash debug features, and both flags are normally better set on the command line rather than within the script itself.Most of this also applies to the <code>ERR</code> trap, though I've seen it used in a few places in shells that lack <code>pipefail</code> or <code>PIPESTATUS</code>. The <code>ERR</code> trap is not POSIX, but <code>set -e</code> is. <code>failglob</code> is another Bash feature that falls into this category (mainly useful for debugging).The <code>set -e</code> feature generates more questions and false bug reports on the Bash mailing list than all other features combined! Please do not rely on <code>set -e</code> for logic in scripts. If you still refuse to take this advice, make sure you understand exactly how it works. See: Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected? and http://www.fvue.nl/wiki/Bash:_Error_handling <code>set -u</code> or <code>set -o nounset</code> Proper control flow and error handling <code>set -u</code> causes attempts to expand unset variables or parameters as fatal errors. Like <code>set -e</code>, it bypasses control flow and exits immediately from the current shell environment. Like non-zero statuses, unset variables are a normal part of most non-trivial shell scripts. Living with <code>set -u</code> requires hacks like <code>${1+\"$1\"}</code> for each expansion that might possibly be unset. Only very current shells guarantee that expanding <code>@</code> or <code>*</code> won't trigger an error when no parameters are set (http://austingroupbugs.net/view.php?id=155, http://www.in-ulm.de/~mascheck/various/bourne_args/). Apparently some find it useful for debugging. See How do I determine whether a variable is already defined? Or a function? for how to properly test for defined variables. Don't use <code>set -u</code>. <code>${var?msg}</code> or <code>${var:?msg}</code> Proper control flow and error handling Like <code>set -u</code>, this expansion causes a fatal error which immediately exits the current shell environment if the given parameter is unset or is null. It prints the error message given, to the right of the operator. If a value is expected and you'd like to create an assertion or cause errors, it's better to test for undefined variables using one of these techniques and handle the error manually, or call a <code>die</code> function. This expansion is defined by POSIX. It's better than <code>set -u</code>, because it's explicit, but not by much. It also allows you to accidentally construct hilariously deceptive error messages: <pre>bash -c 'f() { definitely_not_printf \"${printf:?\"$1\" - No such option}\"; }; f -v'bash: printf: -v - No such option</pre>","tags":["bash","shell","scripting","obsolete","deprecated","outdated"]},{"location":"scripting/obsolete/#frequently-misued","title":"Frequently misued","text":"<p>This table lists features that are used only if you have a specific reason to prefer it over another alternative. These have some legitimate uses if you know what you're doing, such as for those with specific portability requirements, or in order to make use of some subtle behavioral differences. These are frequently (mis)used for no reason. Writing portable scripts that go outside of POSIX features requires knowing how to account for many (often undocumented) differences across many shells. If you do happen to know what you're doing, don't be too surprised if you run across someone telling you not to use these.</p> Syntax Replacement Description <code>function NAME { CMDS; }</code> <code>NAME() COMPOUND-CMD</code> This is the ksh form of function definition created to extend the Bourne and POSIX form with modified behaviors and additional features like local variables. The idea was for new-style functions to be analogous to regular builtins with their own environment and scope, while POSIX-style functions are more like special builtins. <code>function</code> is supported by almost every ksh-derived shell including Bash and Zsh, but isn't specified by POSIX. Bash treats all function styles the same, but this is unusual. <code>function</code> has some preferable characteristics in many ksh variants, making it more portable for scripts that use non-POSIX extensions by some measures. If you're going to use the <code>function</code> keyword, it implies that you're either targeting Ksh specifically, or that you have detailed knowledge of how to compensate for differences across shells. It should always be used consistently with <code>typeset</code>, but never used with <code>declare</code> or <code>local</code>. Also in ksh93, the braces are not a command group, but a required part of the syntax (unlike Bash and others). See shell function definitions <code>typeset</code> <code>declare</code>, <code>local</code>, <code>export</code>, <code>readonly</code> This is closely related to the above, and should often be used together. <code>typeset</code> exists primarily for <code>ksh</code> compatibility, but is marked as \"deprecated\" in Bash (though I don't entirely agree with this). This makes some sense, because future compatibility can't be guaranteed, and any compatibility at all, requires understanding the non-POSIX features of other shells and their differences. Using <code>declare</code> instead of <code>typeset</code> emphasizes your intention to be \"Bash-only\", and definitely breaks everywhere else (except possibly zsh if you're lucky). The issue is further complicated by Dash and the Debian policy requirement for a <code>local</code> builtin, which is itself not entirely compatible with Bash and other shells. <code>let 'EXPR'</code> <code>((EXPR))</code> or <code>[ $((EXPR)) -ne 0 ]</code> <code>let</code> is the \"simple command\" variant of arithmetic evaluation command, which takes regular arguments. Both <code>let</code> and <code>((expr))</code> were present in ksh88, and everything that supports one should support the other. Neither are POSIX. The compound variant is preferable because it doesn't take regular arguments for wordsplitting and globbing, which makes it safer and clearer. It is also usually faster, especially in Bash, where compound commands are typically significantly faster. Some of the (few) reasons for using <code>let</code> are detailed on the let page. See arithmetic evaluation compound command <code>eval</code> Depends. Often code can be restructured to use better alternatives. <code>eval</code> is thrown in here for good measure, as sadly it is so often misused that any use of <code>eval</code> (even the rare clever one) is immediately dismissed as wrong by experts, and among the most immediate solutions abused by beginners. In reality, there are correct ways to use <code>eval</code>, and even cases in which it's necessary, even in sophisticated shells like Bash and Ksh. <code>eval</code> is unusual in that it is less frequently appropriate in more feature-rich shells than in more minimal shells like Dash, where it is used to compensate for more limitations. If you find yourself needing <code>eval</code> too frequently, it might be a sign that you're either better off using a different language entirely, or trying to borrow an idiom from some other paradigm that isn't well suited to the shell language. By the same token, there are some cases in which working too hard to avoid <code>eval</code> ends up adding a lot of complexity and sacrificing all portability. Don't substitute a clever <code>eval</code> for something that's a bit \"too clever\", just to avoid the <code>eval</code>, yet, take reasonable measures to avoid it where it is sensible to do so. See: The eval builtin command and Eval command and security issues.","tags":["bash","shell","scripting","obsolete","deprecated","outdated"]},{"location":"scripting/obsolete/#see-also","title":"See also","text":"<ul> <li>Non-portable syntax and command uses</li> <li>bashchanges</li> <li>Greg's BashFAQ 061: List of essential features added (with the Bash version tag)</li> <li>Bash &lt;-&gt; POSIX Portability guide with a focus on Dash</li> <li>http://mywiki.wooledge.org/BashPitfalls</li> </ul>","tags":["bash","shell","scripting","obsolete","deprecated","outdated"]},{"location":"scripting/posparams/","title":"Handling positional parameters","text":"","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#intro","title":"Intro","text":"<p>The day will come when you want to give arguments to your scripts. These arguments are known as positional parameters. Some relevant special parameters are described below:</p> Parameter(s) Description <code>$0</code> the first positional parameter, equivalent to <code>argv[0]</code> in C, see the first argument <code>$FUNCNAME</code> the function name (attention: inside a function, <code>$0</code> is still the <code>$0</code> of the shell, not the function name) <code>$1 ... $9</code> the argument list elements from 1 to 9 <code>${10} ... ${N}</code> the argument list elements beyond 9 (note the parameter expansion syntax!) <code>$*</code> all positional parameters except <code>$0</code>, see mass usage <code>$@</code> all positional parameters except <code>$0</code>, see mass usage <code>$#</code> the number of arguments, not counting <code>$0</code> <p>These positional parameters reflect exactly what was given to the script when it was called.</p> <p>Option-switch parsing (e.g. <code>-h</code> for displaying help) is not performed at this point.</p> <p>See also the dictionary entry for \"parameter\".</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#the-first-argument","title":"The first argument","text":"<p>The very first argument you can access is referenced as <code>$0</code>. It is usually set to the script's name exactly as called, and it's set on shell initialization:</p> <p>Testscript - it just echos <code>$0</code>:</p> <pre><code>#!/bin/bash\necho \"$0\"\n</code></pre> <p>You see, <code>$0</code> is always set to the name the script is called with (<code>&gt;</code> is the prompt...):</p> <pre><code>&gt; ./testscript\n./testscript\n\n&gt; /usr/bin/testscript\n/usr/bin/testscript\n</code></pre> <p>However, this isn't true for login shells:</p> <pre><code>&gt; echo \"$0\"\n-bash\n</code></pre> <p>In other terms, <code>$0</code> is not a positional parameter, it's a special parameter independent from the positional parameter list. It can be set to anything. In the ideal case it's the pathname of the script, but since this gets set on invocation, the invoking program can easily influence it (the <code>login</code> program does that for login shells, by prefixing a dash, for example).</p> <p>Inside a function, <code>$0</code> still behaves as described above. To get the function name, use <code>$FUNCNAME</code>.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#shifting","title":"Shifting","text":"<p>The builtin command <code>shift</code> is used to change the positional parameter values:</p> <ul> <li><code>$1</code> will be discarded</li> <li><code>$2</code> will become <code>$1</code></li> <li><code>$3</code> will become <code>$2</code></li> <li>...</li> <li>in general: <code>$N</code> will become <code>$N-1</code></li> </ul> <p>The command can take a number as argument: Number of positions to shift. e.g. <code>shift 4</code> shifts <code>$5</code> to <code>$1</code>.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#using-them","title":"Using them","text":"<p>Enough theory, you want to access your script-arguments. Well, here we go.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#one-by-one","title":"One by one","text":"<p>One way is to access specific parameters:</p> <pre><code>#!/bin/bash\necho \"Total number of arguments: $#\"\necho \"Argument 1: $1\"\necho \"Argument 2: $2\"\necho \"Argument 3: $3\"\necho \"Argument 4: $4\"\necho \"Argument 5: $5\"\n</code></pre> <p>While useful in another situation, this way is lacks flexibility. The maximum number of arguments is a fixedvalue - which is a bad idea if you write a script that takes many filenames as arguments.</p> <p>=&gt; forget that one</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#loops","title":"Loops","text":"<p>There are several ways to loop through the positional parameters.</p> <p>You can code a C-style for-loop using <code>$#</code> as the end value. On every iteration, the <code>shift</code>-command is used to shift the argument list:</p> <pre><code>numargs=$#\nfor ((i=1 ; i &lt;= numargs ; i++))\ndo\n echo \"$1\"\n shift\ndone\n</code></pre> <p>Not very stylish, but usable. The <code>numargs</code> variable is used to store the initial value of <code>$#</code> because the shift command will change it as the script runs.</p> <p>Another way to iterate one argument at a time is the <code>for</code> loop without a given wordlist. The loop uses the positional parameters as a wordlist:</p> <pre><code>for arg\ndo\n echo \"$arg\"\ndone\n</code></pre> <p>Advantage: The positional parameters will be preserved</p> <p>The next method is similar to the first example (the <code>for</code> loop), but it doesn't test for reaching <code>$#</code>. It shifts and checks if <code>$1</code> still expands to something, using the test command:</p> <pre><code>while [ \"$1\" ]\ndo\n echo \"$1\"\n shift\ndone\n</code></pre> <p>Looks nice, but has the disadvantage of stopping when <code>$1</code> is empty (null-string). Let's modify it to run as long as <code>$1</code> is defined (but may be null), using parameter expansion for an alternate value:</p> <pre><code>while [ \"${1+defined}\" ]; do\n echo \"$1\"\n shift\ndone\n</code></pre>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#getopts","title":"Getopts","text":"<p>There is a small tutorial dedicated to <code>getopts</code> (under construction).</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#mass-usage","title":"Mass usage","text":"","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#all-positional-parameters","title":"All Positional Parameters","text":"<p>Sometimes it's necessary to just \"relay\" or \"pass\" given arguments to another program. It's very inefficient to do that in one of these loops, as you will destroy integrity, most likely (spaces!).</p> <p>The shell developers created <code>$*</code> and <code>$@</code> for this purpose.</p> <p>As overview:</p> Syntax Effective result <code>$*</code> <code>$1 $2 $3 ... ${N}</code> <code>$@</code> <code>$1 $2 $3 ... ${N}</code> <code>\"$*\"</code> <code>\"$1c$2c$3c...c${N}\"</code> <code>\"$@\"</code> <code>\"$1\" \"$2\" \"$3\" ... \"${N}\"</code> <p>Without being quoted (double quotes), both have the same effect: All positional parameters from <code>$1</code> to the last one used are expanded without any special handling.</p> <p>When the <code>$*</code> special parameter is double quoted, it expands to the equivalent of: <code>\"$1c$2c$3c$4c........$N\"</code>, where 'c' is the first character of <code>IFS</code>.</p> <p>But when the <code>$@</code> special parameter is used inside double quotes, it expands to the equivanent of...</p> <p><code>\"$1\" \"$2\" \"$3\" \"$4\" ..... \"$N\"</code></p> <p>...which reflects all positional parameters as they were set initially and passed to the script or function. If you want to re-use your positional parameters to call another program (for example in a wrapper-script), then this is the choice for you, use double quoted <code>\"$@\"</code>.</p> <p>Well, let's just say: You almost always want a quoted <code>\"$@\"</code>!</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#range-of-positional-parameters","title":"Range Of Positional Parameters","text":"<p>Another way to mass expand the positional parameters is similar to what is possible for a range of characters using substring expansion on normal parameters and the mass expansion range of arrays.</p> <p><code>${@:START:COUNT}</code></p> <p><code>${*:START:COUNT}</code></p> <p><code>\"${@:START:COUNT}\"</code></p> <p><code>\"${*:START:COUNT}\"</code></p> <p>The rules for using <code>@</code> or <code>*</code> and quoting are the same as above. This will expand <code>COUNT</code> number of positional parameters beginning at <code>START</code>. <code>COUNT</code> can be omitted (<code>${@:START}</code>), in which case, all positional parameters beginning at <code>START</code> are expanded.</p> <p>If <code>START</code> is negative, the positional parameters are numbered in reverse starting with the last one.</p> <p><code>COUNT</code> may not be negative, i.e. the element count may not be decremented.</p> <p>Example: START at the last positional parameter:</p> <pre><code>echo \"${@: -1}\"\n</code></pre> <p>Attention: As of Bash 4, a <code>START</code> of <code>0</code> includes the special parameter <code>$0</code>, i.e. the shell name or whatever <code>$0</code> is set to, when the positional parameters are in use. A <code>START</code> of <code>1</code> begins at <code>$1</code>. In Bash 3 and older, both <code>0</code> and <code>1</code> began at <code>$1</code>.</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#setting-positional-parameters","title":"Setting Positional Parameters","text":"<p>Setting positional parameters with command line arguments, is not the only way to set them. The builtin command, set may be used to \"artificially\" change the positional parameters from inside the script or function:</p> <pre><code>set \"This is\" my new \"set of\" positional parameters\n\n# RESULTS IN\n# $1: This is\n# $2: my\n# $3: new\n# $4: set of\n# $5: positional\n# $6: parameters\n</code></pre> <p>It's wise to signal \"end of options\" when setting positional parameters this way. If not, the dashes might be interpreted as an option switch by <code>set</code> itself:</p> <pre><code># both ways work, but behave differently. See the article about the set command!\nset -- ...\nset - ...\n</code></pre> <p>Alternately this will also preserve any verbose (-v) or tracing (-x) flags, which may otherwise be reset by <code>set</code></p> <pre><code>set -$- ...\n</code></pre> <p>FIXME</p> <p>continue</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#production-examples","title":"Production examples","text":"","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#using-a-while-loop","title":"Using a while loop","text":"<p>To make your program accept options as standard command syntax:</p> <p><code>COMMAND [options] &lt;params&gt; # Like 'cat -A file.txt'</code></p> <p>See simple option parsing code below. It's not that flexible. It doesn't auto-interpret combined options (-fu USER) but it works and is a good rudimentary way to parse your arguments.</p> <pre><code>#!/bin/sh\n# Keeping options in alphabetical order makes it easy to add more.\n\nwhile :\ndo\n case \"$1\" in\n -f | --file)\n file=\"$2\" # You may want to check validity of $2\n shift 2\n ;;\n -h | --help)\n display_help # Call your function\n # no shifting needed here, we're done.\n exit 0\n ;;\n -u | --user)\n username=\"$2\" # You may want to check validity of $2\n shift 2\n ;;\n -v | --verbose)\n # It's better to assign a string, than a number like \"verbose=1\"\n # because if you're debugging the script with \"bash -x\" code like this:\n #\n # if [ \"$verbose\" ] ...\n #\n # You will see:\n #\n # if [ \"verbose\" ] ...\n #\n # Instead of cryptic\n #\n # if [ \"1\" ] ...\n #\n verbose=\"verbose\"\n shift\n ;;\n --) # End of all options\n shift\n break;\n -*)\n echo \"Error: Unknown option: $1\" &gt;&amp;2\n exit 1\n ;;\n *) # No more options\n break\n ;;\n esac\ndone\n\n# End of file\n</code></pre>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#filter-unwanted-options-with-a-wrapper-script","title":"Filter unwanted options with a wrapper script","text":"<p>This simple wrapper enables filtering unwanted options (here: <code>-a</code> and <code>--all</code> for <code>ls</code>) out of the command line. It reads the positional parameters and builds a filtered array consisting of them, then calls <code>ls</code> with the new option set. It also respects the <code>--</code> as \"end of options\" for <code>ls</code> and doesn't change anything after it:</p> <pre><code>#!/bin/bash\n\n# simple ls(1) wrapper that doesn't allow the -a option\n\noptions=() # the buffer array for the parameters\neoo=0 # end of options reached\n\nwhile [[ $1 ]]\ndo\n if ! ((eoo)); then\n case \"$1\" in\n -a)\n shift\n ;;\n --all)\n shift\n ;;\n -[^-]*a*|-a?*)\n options+=(\"${1//a}\")\n shift\n ;;\n --)\n eoo=1\n options+=(\"$1\")\n shift\n ;;\n *)\n options+=(\"$1\")\n shift\n ;;\n esac\n else\n options+=(\"$1\")\n\n # Another (worse) way of doing the same thing:\n # options=(\"${options[@]}\" \"$1\")\n shift\n fi\ndone\n\n/bin/ls \"${options[@]}\"\n</code></pre>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#using-getopts","title":"Using getopts","text":"<p>There is a small tutorial dedicated to <code>getopts</code> (under construction).</p>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/posparams/#see-also","title":"See also","text":"<ul> <li>Internal: getopts_tutorial</li> <li>Internal: while_loop</li> <li>Internal: c_for</li> <li>Internal: arrays (for equivalent syntax for mass-expansion)</li> <li>Internal: Substring expansion on a parameter (for equivalent syntax for mass-expansion)</li> <li>Dictionary, internal: parameter</li> </ul>","tags":["bash","shell","scripting","arguments","positional","parameters","options"]},{"location":"scripting/processtree/","title":"Bash and the process tree","text":"","tags":["bash","shell","scripting","processes","pipes","variables","environment"]},{"location":"scripting/processtree/#the-process-tree","title":"The process tree","text":"<p>The processes in UNIX\u00ae are - unlike other systems - organized as a tree. Every process has a parent process that started, or is responsible, for it. Every process has its own context memory (Not the memory where the process stores its data, rather, the memory where data is stored that doesn't directly belong to the process, but is needed to run the process) i.e. The environment.</p> <p>Every process has its own environment space.</p> <p>The environment stores, among other things, data that's useful to us, the environment variables. These are strings in common <code>NAME=VALUE</code> form, but they are not related to shell variables. A variable named <code>LANG</code>, for example, is used by every program that looks it up in its environment to determinate the current locale.</p> <p>Attention: A variable that is set, like with <code>MYVAR=Hello</code>, is not automatically part of the environment. You need to put it into the environment with the bash builtin command <code>export</code>:</p> <pre><code>export MYVAR\n</code></pre> <p>Common system variables like PATH or HOME are usually part of the environment (as set by login scripts or programs).</p>","tags":["bash","shell","scripting","processes","pipes","variables","environment"]},{"location":"scripting/processtree/#executing-programs","title":"Executing programs","text":"<p>All the diagrams of the process tree use names like \"<code>xterm</code>\" or \"<code>bash</code>\", but that's just to make it easier to understand what's going on, it doesn't mean those processes are actually executed.</p> <p>Let's take a short look at what happens when you \"execute a program\" from the Bash prompt, a program like \"ls\":</p> <pre><code>$ ls\n</code></pre> <p>Bash will now perform two steps:</p> <ul> <li>It will make a copy of itself</li> <li>The copy will replace itself with the \"ls\" program</li> </ul> <p>The copy of Bash will inherit the environment from the \"main Bash\" process: All environment variables will also be copied to the new process. This step is called forking.</p> <p>For a short moment, you have a process tree that might look like this...</p> <pre><code>xterm ----- bash ----- bash(copy)\n</code></pre> <p>...and after the \"second Bash\" (the copy) replaces itself with the <code>ls</code> program (the copy execs it), it might look like</p> <pre><code>xterm ----- bash ----- ls\n</code></pre> <p>If everything was okay, the two steps resulted in one program being run. The copy of the environment from the first step (forking) becomes the environment for the final running program (in this case, <code>ls</code>).</p> <p>What is so important about it? In our example, what the program <code>ls</code> does inside its own environment, it can't affect the environment of its parent process (in this case, <code>bash</code>). The environment was copied when ls was executed. Nothing is \"copied back\" to the parent environment when <code>ls</code> terminates.</p>","tags":["bash","shell","scripting","processes","pipes","variables","environment"]},{"location":"scripting/processtree/#bash-playing-with-pipes","title":"Bash playing with pipes","text":"<p>Pipes are a very powerful tool. You can connect the output of one process to the input of another process. We won't delve into piping at this point, we just want to see how it looks in the process tree. Again, we execute some commands, this time, we'll run <code>ls</code> and <code>grep</code>:</p> <pre><code>$ ls | grep myfile\n</code></pre> <p>It results in a tree like this:</p> <pre><code> +-- ls\nxterm ----- bash --|\n +-- grep\n</code></pre> <p>Note once again, <code>ls</code> can't influence the <code>grep</code> environment, <code>grep</code> can't influence the <code>ls</code> environment, and neither <code>grep</code> nor <code>ls</code> can influence the <code>bash</code> environment.</p> <p>How is that related to shell programming?!?</p> <p>Well, imagine some Bash code that reads data from a pipe. For example, the internal command <code>read</code>, which reads data from stdin and puts it into a variable. We run it in a loop here to count input lines:</p> <pre><code>counter=0\n\ncat /etc/passwd | while read; do ((counter++)); done\necho \"Lines: $counter\"\n</code></pre> <p>What? It's 0? Yes! The number of lines might not be 0, but the variable <code>$counter</code> still is 0. Why? Remember the diagram from above? Rewriting it a bit, we have:</p> <pre><code> +-- cat /etc/passwd\nxterm ----- bash --|\n +-- bash (while read; do ((counter++)); done)\n</code></pre> <p>See the relationship? The forked Bash process will count the lines like a charm. It will also set the variable <code>counter</code> as directed. But if everything ends, this extra process will be terminated - your \"counter\" variable is gone. You see a 0 because in the main shell it was 0, and wasn't changed by the child process!</p> <p>So, how do we count the lines? Easy: Avoid the subshell. The details don't matter, the important thing is the shell that sets the counter must be the \"main shell\". For example:</p> <pre><code>counter=0\n\nwhile read; do ((counter++)); done &lt;/etc/passwd\necho \"Lines: $counter\"\n</code></pre> <p>It's nearly self-explanatory. The <code>while</code> loop runs in the current shell, the counter is incremented in the current shell, everything vital happens in the current shell, also the <code>read</code> command sets the variable <code>REPLY</code> (the default if nothing is given), though we don't use it here.</p>","tags":["bash","shell","scripting","processes","pipes","variables","environment"]},{"location":"scripting/processtree/#actions-that-create-a-subshell","title":"Actions that create a subshell","text":"<p>Bash creates subshells or subprocesses on various actions it performs:</p>","tags":["bash","shell","scripting","processes","pipes","variables","environment"]},{"location":"scripting/processtree/#executing-commands","title":"Executing commands","text":"<p>As shown above, Bash will create subprocesses everytime it executes commands. That's nothing new.</p> <p>But if your command is a subprocess that sets variables you want to use in your main script, that won't work.</p> <p>For exactly this purpose, there's the <code>source</code> command (also: the dot <code>.</code> command). Source doesn't execute the script, it imports the other script's code into the current shell:</p> <pre><code>source ./myvariables.sh\n# equivalent to:\n. ./myvariables.sh\n</code></pre>","tags":["bash","shell","scripting","processes","pipes","variables","environment"]},{"location":"scripting/processtree/#pipes","title":"Pipes","text":"<p>The last big section was about pipes, so no example here.</p>","tags":["bash","shell","scripting","processes","pipes","variables","environment"]},{"location":"scripting/processtree/#explicit-subshell","title":"Explicit subshell","text":"<p>If you group commands by enclosing them in parentheses, these commands are run inside a subshell:</p> <pre><code>(echo PASSWD follows; cat /etc/passwd; echo GROUP follows; cat /etc/group) &gt;output.txt\n</code></pre>","tags":["bash","shell","scripting","processes","pipes","variables","environment"]},{"location":"scripting/processtree/#command-substitution","title":"Command substitution","text":"<p>With command substitution you re-use the output of another command as text in your command line, for example to set a variable. The other command is run in a subshell:</p> <pre><code>number_of_users=$(cat /etc/passwd | wc -l)\n</code></pre> <p>Note that, in this example, a second subshell was created by using a pipe in the command substitution:</p> <pre><code> +-- cat /etc/passwd\nxterm ----- bash ----- bash (cmd. subst.) --|\n +-- wc -l\n</code></pre> <p>FIXME</p> <p>to be continued</p>","tags":["bash","shell","scripting","processes","pipes","variables","environment"]},{"location":"scripting/style/","title":"Scripting with style","text":"<p>FIXME</p> <p>continue</p> <p>These are some coding guidelines that helped me to read and understand my own code over the years. They also will help to produce code that will be a bit more robust than \"if something breaks, I know how to fix it\".</p> <p>This is not a bible, of course. But I have seen so much ugly and terrible code (not only in shell) during all the years, that I'm 100% convinced there needs to be some code layout and style. No matter which one you use, use it throughout your code (at least don't change it within the same shellscript file); don't change your code layout with your mood.</p> <p>Some good code layout helps you to read your own code after a while. And of course it helps others to read the code.</p>"},{"location":"scripting/style/#indentation-guidelines","title":"Indentation guidelines","text":"<p>Indentation is nothing that technically influences a script, it's only for us humans.</p> <p>I'm used to seeing/using indentation of two space characters (though many may prefer 4 spaces, see below in the discussion section):</p> <ul> <li>it's easy and fast to type</li> <li>it's not a hard-tab that's displayed differently in different environments</li> <li>it's wide enough to give a visual break and small enough to not waste too much space on the line</li> </ul> <p>Speaking of hard-tabs: Avoid them if possible. They only make trouble. I can imagine one case where they're useful: Indenting here-documents.</p>"},{"location":"scripting/style/#breaking-up-lines","title":"Breaking up lines","text":"<p>Whenever you need to break lines of long code, you should follow one of these two rules:</p> <p>Indention using command width:</p> <pre><code>activate some_very_long_option \\\n some_other_option\n</code></pre> <p>Indention using two spaces:</p> <pre><code>activate some_very_long_option \\\n some_other_option\n</code></pre> <p>Personally, with some exceptions, I prefer the first form because it supports the visual impression of \"these belong together\".</p>"},{"location":"scripting/style/#breaking-compound-commands","title":"Breaking compound commands","text":"<p>Compound commands 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>"},{"location":"scripting/style/#symbolic","title":"Symbolic","text":"<pre><code>HEAD_KEYWORD parameters; BODY_BEGIN\n BODY_COMMANDS\nBODY_END\n</code></pre>"},{"location":"scripting/style/#ifthenelifelse","title":"if/then/elif/else","text":"<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> <pre><code>if ...; then\n ...\nelif ...; then\n ...\nelse\n ...\nfi\n</code></pre>"},{"location":"scripting/style/#for","title":"for","text":"<pre><code>for f in /etc/*; do\n ...\ndone\n</code></pre>"},{"location":"scripting/style/#whileuntil","title":"while/until","text":"<pre><code>while [[ $answer != [YyNn] ]]; do\n ...\ndone\n</code></pre>"},{"location":"scripting/style/#the-case-construct","title":"The case construct","text":"<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> <pre><code>case $input in\n hello)\n echo \"You said hello\"\n ;;\n bye)\n echo \"You said bye\"\n if foo; then\n bar\n fi\n ;;\n *)\n echo \"You said something weird...\"\n ;;\nesac\n</code></pre> <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>"},{"location":"scripting/style/#syntax-and-coding-guidelines","title":"Syntax and coding guidelines","text":""},{"location":"scripting/style/#cryptic-constructs","title":"Cryptic constructs","text":"<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>"},{"location":"scripting/style/#variable-names","title":"Variable names","text":"<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, do not use reserved variable names (see SUS 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> </li> </ul>"},{"location":"scripting/style/#binbash","title":"!/bin/bash","text":""},{"location":"scripting/style/#the-prefix-my_","title":"the prefix 'MY_'","text":"<p>MY_LOG_DIRECTORY=/var/adm/</p> <p>for file in \"$MY_LOG_DIRECTORY\"/*; do echo \"Found Logfile: $file\" done</p>"},{"location":"scripting/style/#variable-initialization","title":"Variable initialization","text":"<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 environment variable to the script. If you blindly assume that all variables you use for the first time are empty, anybody can inject content into a variable by passing it via the environment.</p> <p>The solution is simple and effective: Initialize them</p> <pre><code>my_input=\"\"\nmy_array=()\nmy_number=0\n</code></pre> <p>If you do that for every variable you use, then you also have some in-code documentation for them.</p>"},{"location":"scripting/style/#parameter-expansion","title":"Parameter expansion","text":"<p>Unless you are really sure what you're doing, quote every parameter expansion.</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> <pre><code>list=\"one two three\"\n\n# you MUST NOT quote $list here\nfor word in $list; do\n ...\ndone\n</code></pre>"},{"location":"scripting/style/#function-names","title":"Function names","text":"<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>do not use command names for your functions. 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>"},{"location":"scripting/style/#command-substitution","title":"Command substitution","text":"<p>As noted in the article about command substitution, 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>"},{"location":"scripting/style/#eval","title":"Eval","text":"<p>Well, like Greg says: \"If eval is the answer, surely you are asking the wrong question.\"</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>"},{"location":"scripting/style/#basic-structure","title":"Basic structure","text":"<p>The basic structure of a script simply reads:</p> <pre><code>#!SHEBANG\n\nCONFIGURATION_VARIABLES\n\nFUNCTION_DEFINITIONS\n\nMAIN_CODE\n</code></pre>"},{"location":"scripting/style/#the-shebang","title":"The shebang","text":"<p>If possible (I know it's not always possible!), use a shebang.</p> <p>Be careful with <code>/bin/sh</code>: The argument that \"on Linux <code>/bin/sh</code> is Bash\" is a lie (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>"},{"location":"scripting/style/#configuration-variables","title":"Configuration variables","text":"<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>"},{"location":"scripting/style/#function-definitions","title":"Function definitions","text":"<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 grouping compound command):</p> <pre><code>getargs() {\n ...\n}\n</code></pre> <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>"},{"location":"scripting/style/#behaviour-and-robustness","title":"Behaviour and robustness","text":""},{"location":"scripting/style/#fail-early","title":"Fail early","text":"<p>Fail early, 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 before your script begins its work in a potentially broken state.</p>"},{"location":"scripting/style/#availability-of-commands","title":"Availability of commands","text":"<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> <pre><code>my_needed_commands=\"sed awk lsof who\"\n\nmissing_counter=0\nfor needed_command in $my_needed_commands; do\n if ! hash \"$needed_command\" &gt;/dev/null 2&gt;&amp;1; then\n printf \"Command not found in PATH: %s\\n\" \"$needed_command\" &gt;&amp;2\n ((missing_counter++))\n fi\ndone\n\nif ((missing_counter &gt; 0)); then\n printf \"Minimum %d commands are missing in PATH, aborting\\n\" \"$missing_counter\" &gt;&amp;2\n exit 1\nfi\n</code></pre>"},{"location":"scripting/style/#exit-meaningfully","title":"Exit meaningfully","text":"<p>The exit code 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, and only this, will enable the calling component to check the operation status of your script.</p> <p>You know: \"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.\" -- Robert Firth</p>"},{"location":"scripting/style/#misc","title":"Misc","text":""},{"location":"scripting/style/#output-and-appearance","title":"Output and appearance","text":"<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 save the terminal content and restore it 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>"},{"location":"scripting/style/#input","title":"Input","text":"<ul> <li>never blindly assume anything. If you want the user to input a number, check for numeric input, leading zeros, etc. If you have specific format or content needs, always validate the input!</li> </ul>"},{"location":"scripting/style/#tooling","title":"Tooling","text":"<ul> <li>some of these guidelines, such as indentation, positioning of \"body-introducing\" keywords, and portable function declarations, can be enforced by shfmt</li> </ul>"},{"location":"scripting/terminalcodes/","title":"Terminal codes (ANSI/VT100) introduction","text":"<p>Terminal (control) codes are used to issue specific commands to your terminal. This can be related to switching colors or positioning the cursor, i.e. anything that can't be done by the application itself.</p>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#how-it-technically-works","title":"How it technically works","text":"<p>A terminal control code is a special sequence of characters that is printed (like any other text). If the terminal understands the code, it won't display the character-sequence, but will perform some action. You can print the codes with a simple <code>echo</code> command.</p> <p>Note: I see codes referenced as \"Bash colors\" sometimes (several \"Bash tutorials\" etc...): That's a completely incorrect definition.</p>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#the-tput-command","title":"The tput command","text":"<p>Because there's a large number of different terminal control languages, usually a system has an intermediate communication layer. The real codes are looked up in a database for the currently detected terminal type and you give standardized requests to an API or (from the shell) to a command.</p> <p>One of these commands is <code>tput</code>. Tput accepts a set of acronyms called capability names and any parameters, if appropriate, then looks up the correct escape sequences for the detected terminal in the <code>terminfo</code> database and prints the correct codes (the terminal hopefully understands).</p>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#the-codes","title":"The codes","text":"<p>In this list I'll focus on ANSI/VT100 control codes for the most common actions - take it as quick reference. The documentation of your terminal or the <code>terminfo</code> database is always the preferred source when something is unclear! Also the <code>tput</code> acronyms are usually the ones dedicated for ANSI escapes!</p> <p>I listed only the most relevant codes, of course, any ANSI terminal understands many more! But let's keep the discussion centered on common shell scripting ;-)</p> <p>If I couldn't find a matching ANSI escape, you'll see a :?: as the code. Feel free to mail me or fix it.</p> <p>The ANSI codes always start with the ESC character. (ASCII 0x1B or octal 033) This isn't part of the list, but you should avoid using the ANSI codes directly - use the <code>tput</code> command!</p> <p>All codes that can be used with <code>tput</code> can be found in terminfo(5). (on OpenBSD at least) See OpenBSD's terminfo(5) under the Capabilities section. The cap-name is the code to use with tput. A description of each code is also provided.</p>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#general-useful-ascii-codes","title":"General useful ASCII codes","text":"<p>The Ctrl-Key representation is simply associating the non-printable characters from ASCII code 1 with the printable (letter) characters from ASCII code 65 (\"A\"). ASCII code 1 would be <code>^A</code> (Ctrl-A), while ASCII code 7 (BEL) would be <code>^G</code> (Ctrl-G). This is a common representation (and input method) and historically comes from one of the VT series of terminals.</p> Name decimal octal hex C-escape Ctrl-Key Description <code>BEL</code> 7 007 0x07 <code>\\a</code> <code>^G</code> Terminal bell <code>BS</code> 8 010 0x08 <code>\\b</code> <code>^H</code> Backspace <code>HT</code> 9 011 0x09 <code>\\t</code> <code>^I</code> Horizontal TAB <code>LF</code> 10 012 0x0A <code>\\n</code> <code>^J</code> Linefeed (newline) <code>VT</code> 11 013 0x0B <code>\\v</code> <code>^K</code> Vertical TAB <code>FF</code> 12 014 0x0C <code>\\f</code> <code>^L</code> Formfeed (also: New page <code>NP</code>) <code>CR</code> 13 015 0x0D <code>\\r</code> <code>^M</code> Carriage return <code>ESC</code> 27 033 0x1B <code>&lt;none&gt;</code> <code>^[</code> Escape character <code>DEL</code> 127 177 0x7F <code>&lt;none&gt;</code> <code>&lt;none&gt;</code> Delete character","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#cursor-handling","title":"Cursor handling","text":"ANSI terminfo equivalent Description <code>[ &lt;X&gt; ; &lt;Y&gt; H</code><code>[ &lt;X&gt; ; &lt;Y&gt; f</code> <code>cup &lt;X&gt; &lt;Y&gt;</code> Home-positioning to <code>X</code> and <code>Y</code> coordinates:!: it seems that ANSI uses 1-1 as home while <code>tput</code> uses 0-0 <code>[ H</code> <code>home</code> Move cursor to home position (0-0) <code>7</code> <code>sc</code> Save current cursor position <code>8</code> <code>rc</code> Restore saved cursor position :?: most likely a normal code like <code>\\b</code> <code>cub1</code> move left one space (backspace) VT100 <code>[ ? 25 l</code> <code>civis</code> make cursor invisible VT100 <code>[ ? 25 h</code> <code>cvvis</code> make cursor visible","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#erasing-text","title":"Erasing text","text":"ANSI terminfo equivalent Description <code>[ K</code><code>[ 0 K</code> <code>el</code> Clear line from current cursor position to end of line <code>[ 1 K</code> <code>el1</code> Clear line from beginning to current cursor position <code>[ 2 K</code> <code>el2</code> :?: Clear whole line (cursor position unchanged)","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#general-text-attributes","title":"General text attributes","text":"ANSI terminfo equivalent Description <code>[ 0 m</code> <code>sgr0</code> Reset all attributes <code>[ 1 m</code> <code>bold</code> Set \"bright\" attribute <code>[ 2 m</code> <code>dim</code> Set \"dim\" attribute <code>[ 3 m</code> <code>smso</code> Set \"standout\" attribute <code>[ 4 m</code> set <code>smul</code> unset <code>rmul</code> :?: Set \"underscore\" (underlined text) attribute <code>[ 5 m</code> <code>blink</code> Set \"blink\" attribute <code>[ 7 m</code> <code>rev</code> Set \"reverse\" attribute <code>[ 8 m</code> <code>invis</code> Set \"hidden\" attribute","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#foreground-coloring","title":"Foreground coloring","text":"ANSI terminfo equivalent Description <code>[ 3 0 m</code> <code>setaf 0</code> Set foreground to color #0 - black <code>[ 3 1 m</code> <code>setaf 1</code> Set foreground to color #1 - red <code>[ 3 2 m</code> <code>setaf 2</code> Set foreground to color #2 - green <code>[ 3 3 m</code> <code>setaf 3</code> Set foreground to color #3 - yellow <code>[ 3 4 m</code> <code>setaf 4</code> Set foreground to color #4 - blue <code>[ 3 5 m</code> <code>setaf 5</code> Set foreground to color #5 - magenta <code>[ 3 6 m</code> <code>setaf 6</code> Set foreground to color #6 - cyan <code>[ 3 7 m</code> <code>setaf 7</code> Set foreground to color #7 - white <code>[ 3 9 m</code> <code>setaf 9</code> Set default color as foreground color","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#background-coloring","title":"Background coloring","text":"ANSI terminfo equivalent Description <code>[ 4 0 m</code> <code>setab 0</code> Set background to color #0 - black <code>[ 4 1 m</code> <code>setab 1</code> Set background to color #1 - red <code>[ 4 2 m</code> <code>setab 2</code> Set background to color #2 - green <code>[ 4 3 m</code> <code>setab 3</code> Set background to color #3 - yellow <code>[ 4 4 m</code> <code>setab 4</code> Set background to color #4 - blue <code>[ 4 5 m</code> <code>setab 5</code> Set background to color #5 - magenta <code>[ 4 6 m</code> <code>setab 6</code> Set background to color #6 - cyan <code>[ 4 7 m</code> <code>setab 7</code> Set background to color #7 - white <code>[ 4 9 m</code> <code>setab 9</code> Set default color as background color","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#misc-codes","title":"Misc codes","text":"","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#saverestore-screen","title":"Save/restore screen","text":"<p>Used capabilities: <code>smcup</code>, <code>rmcup</code></p> <p>You've undoubtedly already encountered programs that restore the terminal contents after they do their work (like <code>vim</code>). This can be done by the following commands:</p> <pre><code># save, clear screen\ntput smcup\nclear\n\n# example \"application\" follows...\nread -n1 -p \"Press any key to continue...\"\n# example \"application\" ends here\n\n# restore\ntput rmcup\n</code></pre> <p>These features require that certain capabilities exist in your termcap/terminfo. While <code>xterm</code> and most of its clones (<code>rxvt</code>, <code>urxvt</code>, etc) will support the instructions, your operating system may not include references to them in its default xterm profile. (FreeBSD, in particular, falls into this category.) If <code>tput smcup</code> appears to do nothing for you, and you don't want to modify your system termcap/terminfo data, and you KNOW that you are using a compatible xterm application, the following may work for you:</p> <pre><code>echo -e '\\033[?47h' # save screen\necho -e '\\033[?47l' # restore screen\n</code></pre> <p>Certain software uses these codes (via their termcap capabilities) as well. You may have seen the screen save/restore in <code>less</code>, <code>vim</code>, <code>top</code>, <code>screen</code> and others. Some of these applications may also provide configuration options to disable this behaviour. For example, <code>less</code> has a <code>-X</code> option for this, which can also be set in an environment variable:</p> <pre><code>export LESS=X\nless /path/to/file\n</code></pre> <p>Similarly, <code>vim</code> can be configured not to \"restore\" the screen by adding the following to your <code>~/.vimrc</code>:</p> <pre><code>set t_ti= t_te=\n</code></pre>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#additional-colors","title":"Additional colors","text":"<p>Some terminal emulators support additional colors. The most common extension used by xterm-compatible terminals supports 256 colors. These can be generated by <code>tput</code> with <code>seta{f,b} [0-255]</code> when the <code>TERM</code> value has a <code>-256color</code> suffix. Some terminals also support full 24-bit colors, and any X11 color code can be written directly into a special escape sequence. (More infos) Only a few programs make use of anything beyond 256 colors, and tput doesn't know about them. Colors beyond 16 usually only apply to modern terminal emulators running in graphical environments.</p> <p>The Virtual Terminal implemented in the Linux kernel supports only 16 colors, and the usual default terminfo entry for <code>TERM=linux</code> defines only 8. There is sometimes an alternate \"linux-16color\" that you can switch to, to get the other 8 colors.</p>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#bash-examples","title":"Bash examples","text":"","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#hardcoded-colors","title":"Hardcoded colors","text":"<pre><code>printf '%b\\n' 'It is \\033[31mnot\\033[39m intelligent to use \\033[32mhardcoded ANSI\\033[39m codes!'\n</code></pre>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#colors-using-tput","title":"Colors using tput","text":"<p>Directly inside the echo:</p> <pre><code>echo \"TPUT is a $(tput setaf 2)nice$(tput setaf 9) and $(tput setaf 5)user friendly$(tput setaf 9) terminal capability database.\"\n</code></pre> <p>With preset variables:</p> <pre><code>COL_NORM=\"$(tput setaf 9)\"\nCOL_RED=\"$(tput setaf 1)\"\nCOL_GREEN=\"$(tput setaf 2)\"\necho \"It's ${COL_RED}red${COL_NORM} and ${COL_GREEN}green${COL_NORM} - have you seen?\"\n</code></pre>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#misc","title":"Misc","text":"<p>HOME function</p> <pre><code>home() {\n # yes, actually not much shorter ;-)\n tput home\n}\n</code></pre>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#silly-but-nice-effect","title":"Silly but nice effect","text":"<pre><code>#!/bin/bash\n\nDATA[0]=\" _/ _/ _/ _/ \"\nDATA[1]=\" _/_/_/_/_/ _/_/_/ _/_/_/ _/_/_/ _/_/_/ \"\nDATA[2]=\" _/ _/ _/ _/ _/ _/ _/_/ _/ _/\"\nDATA[3]=\"_/_/_/_/_/ _/ _/ _/ _/ _/_/ _/ _/ \"\nDATA[4]=\" _/ _/ _/_/_/ _/_/_/ _/_/_/ _/ _/ \"\n\n# virtual coordinate system is X*Y ${#DATA} * 5\n\nREAL_OFFSET_X=0\nREAL_OFFSET_Y=0\n\ndraw_char() {\n V_COORD_X=$1\n V_COORD_Y=$2\n\n tput cup $((REAL_OFFSET_Y + V_COORD_Y)) $((REAL_OFFSET_X + V_COORD_X))\n\n printf %c ${DATA[V_COORD_Y]:V_COORD_X:1}\n}\n\n\ntrap 'exit 1' INT TERM\ntrap 'tput setaf 9; tput cvvis; clear' EXIT\n\ntput civis\nclear\n\nwhile :; do\n\nfor ((c=1; c &lt;= 7; c++)); do\n tput setaf $c\n for ((x=0; x&lt;${#DATA[0]}; x++)); do\n for ((y=0; y&lt;=4; y++)); do\n draw_char $x $y\n done\n done\ndone\n\ndone\n</code></pre>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"scripting/terminalcodes/#mandelbrot-set","title":"Mandelbrot set","text":"<p>This is a slightly modified version of Charles Cooke's colorful Mandelbrot plot scripts (original w/ screenshot) -- ungolfed, optimized a bit, and without hard-coded terminal escapes. The <code>colorBox</code> function is memoized to collect <code>tput</code> output only when required and output a new escape only when a color change is needed. This limits the number of <code>tput</code> calls to at most 16, and reduces raw output by more than half. The <code>doBash</code> function uses integer arithmetic, but is still ksh93-compatible (run as e.g. <code>bash ./mandelbrot</code> to use it). The ksh93-only floating-point <code>doKsh</code> is almost 10x faster than <code>doBash</code> (thus the ksh shebang by default), but uses only features that don't make the Bash parser crash.</p> <pre><code>#!/usr/bin/env ksh\n\n# Charles Cooke's 16-color Mandelbrot\n# http://earth.gkhs.net/ccooke/shell.html\n# Combined Bash/ksh93 flavors by Dan Douglas (ormaaj)\n\nfunction doBash {\n typeset P Q X Y a b c i v x y\n for ((P=10**8,Q=P/100,X=320*Q/cols,Y=210*Q/lines,y=-105*Q,v=-220*Q,x=v;y&lt;105*Q;x=v,y+=Y)); do\n for ((;x&lt;P;a=b=i=c=0,x+=X)); do\n for ((;a**2+b**2&lt;4*P**2&amp;&amp;i++&lt;99;a=((c=a)**2-b**2)/P+x,b=2*c*b/P+y)); do :\n done\n colorBox $((i&lt;99?i%16:0))\n done\n echo\n done\n}\n\nfunction doKsh {\n integer i\n float a b c x=2.2 y=-1.05 X=3.2/cols Y=2.1/lines\n while\n for ((a=b=i=0;(c=a)**2+b**2&lt;=2&amp;&amp;i++&lt;99&amp;&amp;(a=a**2-b**2+x,b=2*c*b+y);)); do :\n done\n . colorBox $((i&lt;99?i%16:0))\n if ((x&lt;1?!(x+=X):(y+=Y,x=-2.2))); then\n print\n ((y&lt;1.05))\n fi\n do :\n done\n}\n\nfunction colorBox {\n (($1==lastclr)) || printf %s \"${colrs[lastclr=$1]:=$(tput setaf \"$1\")}\"\n printf '\\u2588'\n}\n\nunset -v lastclr\n((cols=$(tput cols)-1, lines=$(tput lines)))\ntypeset -a colrs\ntrap 'tput sgr0; echo' EXIT\n${KSH_VERSION+. doKsh} ${BASH_VERSION+doBash}\n</code></pre> <p>A much more sophisticated version by Roland Mainz can be found here</p>","tags":["bash","shell","scripting","colors","cursor","control","vt100","ansi"]},{"location":"snipplets/","title":"Small code snipplets","text":"<p>These snipplets are not meant as HowTo or Tutorial or FAQ. Mostly they are only a line of code and a short comment.</p> <p>See it more like an initial idea to give you a start.</p>","tags":["bash","shell","scripting","code","download","snipplet","example"]},{"location":"snipplets/add_color_to_your_scripts/","title":"Add Color to your scripts","text":"<p>---- dataentry snipplet ---- snipplet_tags : terminal, color LastUpdate_dt : 2013-03-23 Contributors : Frank Lazzarini, Dan Douglas type : snipplet</p> <p>Make your scripts output more readable using bash colors. Simply add these variables to your script, and you will be able to echo in color. (I haven't added all the colors available, just some basics)</p> <pre><code># Colors\nESC_SEQ=\"\\x1b[\"\nCOL_RESET=$ESC_SEQ\"39;49;00m\"\nCOL_RED=$ESC_SEQ\"31;01m\"\nCOL_GREEN=$ESC_SEQ\"32;01m\"\nCOL_YELLOW=$ESC_SEQ\"33;01m\"\nCOL_BLUE=$ESC_SEQ\"34;01m\"\nCOL_MAGENTA=$ESC_SEQ\"35;01m\"\nCOL_CYAN=$ESC_SEQ\"36;01m\"\n</code></pre> <p>Now if you want to output some text in color use echo -e instead of just echo. And always remember to use the \\$COL_RESET variable to reset the color changes in bash. Like so ....</p> <pre><code>echo -e \"$COL_RED This is red $COL_RESET\"\necho -e \"$COL_BLUE This is blue $COL_RESET\"\necho -e \"$COL_YELLOW This is yellow $COL_RESET\"\n</code></pre> <p>But also see the notes in the article about using terminalcodes about generating codes and hardwiring codes.</p> <p>This snipplet sets up associative arrays for basic color codes using <code>tput</code> for Bash, ksh93 or zsh. You can pass it variable names to correspond with a collection of codes. There's a <code>main</code> function with example usage.</p> <pre><code>#!/usr/bin/env bash\n\n${ZSH_VERSION+false} || emulate ksh\n${BASH_VERSION+shopt -s lastpipe extglob}\n\n# colorSet [ --setaf | --setab | --misc ] var\n# Assigns the selected set of escape mappings to the given associative array names.\nfunction colorSet {\n typeset -a clrs msc\n typeset x\n clrs=(black red green orange blue magenta cyan grey darkgrey ltred ltgreen yellow ltblue ltmagenta ltcyan white)\n msc=(sgr0 bold dim smul blink rev invis)\n\n while ! ${2:+false}; do\n ${KSH_VERSION:+eval typeset -n \"$2\"=\\$2}\n case ${1#--} in\n setaf|setab)\n for x in \"${!clrs[@]}\"; do\n eval \"$2\"'[${clrs[x]}]=$(tput \"${1#--}\" \"$x\")'\n done\n ;;\n misc)\n for x in \"${msc[@]}\"; do\n eval \"$2\"'[$x]=$(tput \"$x\")'\n done\n ;;\n *)\n return 1\n esac\n shift 2\n done\n}\n\n# Example code\nfunction main {\n typeset -A fgColors bgColors miscEscapes\n if colorSet --setaf fgColors --setab bgColors --misc miscEscapes; then\n if ! ${1:+${fgColors[$1]:+false}}; then\n printf '%s%s%s\\n' \"${fgColors[$1]}\" \"this text is ${1}\" \"${miscEscapes[sgr0]}\" &gt;&amp;3\n else\n printf '%s, %s\\n' \"${1:-Empty}\" 'no such color.'\n typeset x y\n for x in fgColors bgColors miscEscapes; do\n typeset -a keys\n eval 'keys=(\"${!'\"$x\"'[@]}\")'\n printf '%s=( ' \"$x\"\n for y in \"${keys[@]}\"; do\n eval 'printf \"[%q]=%q \" \"$y\" \"${'\"$x\"'[$y]}\"'\n done\n printf ')\\n'\n done\n return 1\n fi\n else\n echo 'Failed setting color arrays.'\n return 1\n fi 3&gt;&amp;1 &gt;&amp;2\n}\n\nmain \"$@\"\n\n# vim: set fenc=utf-8 ff=unix ft=sh :\n</code></pre>"},{"location":"snipplets/awkcsv/","title":"Using <code>awk</code> to deal with CSV that uses quoted/unquoted delimiters","text":"<p>CSV files are a mess, yes.</p> <p>Assume you have CSV files that use the comma as delimiter and quoted data fields that can contain the delimiter.</p> <pre><code>\"first\", \"second\", \"last\"\n\"fir,st\", \"second\", \"last\"\n\"firtst one\", \"sec,ond field\", \"final,ly\"\n</code></pre> <p>Simply using the comma as separator for <code>awk</code> won't work here, of course.</p> <p>Solution: Use the field separator <code>\", \"|^\"|\"$</code> for <code>awk</code>.</p> <p>This is an OR-ed list of 3 possible separators:</p> <code>\", \"</code> matches the area between the datafields <code>^\"</code> matches the area left of the first datafield <code>\"$</code> matches the area right of the last data field <p>You can tune these delimiters if you have other needs (for example if you don't have a space after the commas).</p> <p>Test:</p> <p>The <code>awk</code> command used for the CSV above just prints the fileds separated by <code>###</code> to see what's going on:</p> <pre><code>$ awk -v FS='\", \"|^\"|\"$' '{print $2\"###\"$3\"###\"$4}' data.csv\nfirst###second###last\nfir,st###second###last\nfirtst one###sec,ond field###final,ly\n</code></pre> <p>ATTENTION If the CSV data changes its format every now and then (for example it only quotes the data fields if needed, not always), then this way will not work.</p>","tags":["awk","csv"]},{"location":"snipplets/filesize/","title":"Show size of a file","text":"<p>---- dataentry snipplet ---- snipplet_tags: files, file size LastUpdate_dt: 2010-07-31 Contributors: Frank Lazzarini type: snipplet</p> <p>This is a simple snippet to echo the size of a file in bytes.</p> <pre><code>#!/bin/bash\nFILENAME=/home/heiko/dummy/packages.txt\nFILESIZE=$(wc -c &lt; \"$FILENAME\")\n# non standard way (GNU stat): FILESIZE=$(stat -c%s \"$FILENAME\")\n\necho \"Size of $FILENAME = $FILESIZE bytes.\"\n</code></pre>"},{"location":"snipplets/kill_bg_job_without_message/","title":"Kill a background job without a message","text":"<p>---- dataentry snipplet ---- snipplet_tags: kill, process management, jobs LastUpdate_dt: 2010-07-31 Contributors: Jan Schampera type: snipplet</p> <p>When you start background jobs from within a script (non-interactive shell) and kill it afterwards, you will get a message from the shell that the process was terminated.</p> <p>Example:</p> <pre><code>#!/bin/bash\n\n# example background process\nsleep 300 &amp;\n\n# get the PID\nBG_PID=$!\n\n# kill it, hard and mercyless\nkill -9 $BG_PID\n\necho \"Yes, we killed it\"\n</code></pre> <p>You will get something like this:</p> <pre><code>$ ./bg_kill1.sh\n./bg_kill1.sh: line 11: 3413 Killed sleep 300\nYes, we killed it\n</code></pre> <p>This is more or less a normal message. And it can't be easily redirected since it's the shell itself that yells this message, not the command <code>kill</code> or something else. You would have to redirect the whole script's output.</p> <p>It's also useless to temporarily redirect <code>stderr</code> when you call the <code>kill</code> command, since the successful termination of the job, the termination of the <code>kill</code> command and the message from the shell may not happen at the same time. And a blind <code>sleep</code> after the <code>kill</code> would be just a workaround.</p> <p>The solution is relatively easy: The shell spits that message because it controls the background job, and when it terminates, the shell will tell you whenever possible. Now you just need to tell your shell that it is no longer responsible for that background process. This is done by the <code>disown</code> command, which can take an internal shell job number (like <code>%1</code>) or a process ID as argument.</p> <pre><code>#!/bin/bash\n\n# example background process\nsleep 300 &amp;\n\n# get the PID\nBG_PID=$!\n\n### HERE, YOU TELL THE SHELL TO NOT CARE ANY MORE ###\ndisown $BG_PID\n###\n\n\n# kill it, hard and mercyless, now without a trace\nkill -9 $BG_PID\n\necho \"Yes, we killed it\"\n</code></pre> <p>That way, you can run and kill background processes without disturbing messages.</p>"},{"location":"snipplets/largestfile/","title":"Get largest file","text":"<p>---- dataentry snipplet ---- snipplet_tags: directory, recursive, find, crawl LastUpdate_dt: 2013-03-23 Contributors: Dan Douglas type: snipplet</p> <p>One basic pattern for recursive directory traversal with operations on files at each node. This gets the largest file in each subdirectory. Toggling some small details will make it return the smallest, or traverse breadth-first instead of depth-first.</p> <pre><code>#!/usr/bin/env bash\n# GNU find + bash4 / ksh93v / zsh\n# Get the largest file matching pattern in the given directories recursively\n${ZSH_VERSION+false} || emulate ksh\n${BASH_VERSION+shopt -s lastpipe extglob}\n\nfunction getLargest {\n typeset -A cur top || return\n typeset dir x\n for dir in \"$2\"/*/; do\n [[ -d $dir ]] || return 0\n getLargest \"$1\" \"${dir%/}\" || return\n top[size]=-1\n find \"$dir\" -maxdepth 1 -type f -name \"$1\" -printf '%s\\0%f\\0' | {\n while :; do\n for x in cur\\[{size,name}\\]; do\n IFS= read -rd '' \"$x\" || break 2\n done\n if (( cur[size] &gt; top[size] )); then\n top[size]=${cur[size]} top[name]=${cur[name]}\n fi\n done\n printf '%q\\n' \"${dir}${top[name]}\"\n }\n done\n}\n\n# main pattern dir [ dir ... ]\nfunction main {\n if [[ -n $1 ]]; then\n typeset dir pattern=$1\n shift\n for dir; do\n [[ -d $dir ]] || return\n getLargest \"$pattern\" \"$dir\"\n done\n else\n return 1\n fi\n}\n\nmain \"$@\"\n\n# vim: set fenc=utf-8 ff=unix ft=sh :\n</code></pre>"},{"location":"snipplets/largestfile/#more-examples","title":"More examples","text":"<ul> <li>http://mywiki.wooledge.org/BashFAQ/003</li> <li>http://mywiki.wooledge.org/UsingFind</li> </ul>"},{"location":"snipplets/pause_command/","title":"Pausing a script (like MSDOS pause command)","text":"<p>---- dataentry snipplet ---- snipplet_tags: terminal, pause, input LastUpdate_dt: 2010-07-31 Contributors: Jan Schampera type: snipplet</p> <p>From the example section of the read command, something that acts similar to the MSDOS <code>pause</code> command:</p> <pre><code>pause() {\n local dummy\n read -s -r -p \"Press any key to continue...\" -n 1 dummy\n}\n</code></pre>"},{"location":"snipplets/prargs/","title":"Print argument list for testing","text":"<p>---- dataentry snipplet ---- snipplet_tags: debug, arguments LastUpdate_dt: 2013-03-23 Contributors: Snappy (IRC), Dan Douglas type: snipplet</p> <p>Sometimes you might find it useful to see how arguments passed to a program arrive there.</p> <p>Check this script (save it as script file or make a function):</p> <pre><code>printf '\"%b\"\\n' \"$0\" \"$@\" | nl -v0 -s\": \"\n</code></pre> <p>It uses the printf command to generate a list of arguments, even with escape sequences interpreted. This list is shown formatted by the nl(1) utility.</p> <p>Another alternative with colorized output. If run in Bash, it temporarily disables all debug output for itself, including the test that determines whether to hide debug output. In ksh, tracing would have to be enabled on the function to show debug output, so it works out to being equivalent.</p> <pre><code># Bash or ksh93 debugging function for colored display of argv.\n# Optionally set OFD to the desired output file descriptor.\nfunction args {\n { BASH_XTRACEFD=3 command eval ${BASH_VERSION+\"$(&lt;/dev/fd/0)\"}; } &lt;&lt;-'EOF' 3&gt;/dev/null\n case $- in *x*)\n set +x\n trap 'trap RETURN; set -x' RETURN\n esac\nEOF\n\n [[ ${OFD-1} == +([0-9]) ]] || return\n\n if [[ -t ${OFD:-2} ]]; then\n typeset -A clr=([green]=$(tput setaf 2) [sgr0]=$(tput sgr0))\n else\n typeset clr\n fi\n\n if ! ${1+false}; then\n printf -- \"${clr[green]}&lt;${clr[sgr0]}%s${clr[green]}&gt;${clr[sgr0]} \" \"$@\"\n echo\n else\n echo 'no args.'\n fi &gt;&amp;\"${OFD:-2}\"\n}\n</code></pre>"},{"location":"snipplets/print_horizontal_line/","title":"Print a horizontal line","text":"<p>---- dataentry snipplet ---- snipplet_tags: terminal, line LastUpdate_dt: 2010-07-31 Contributors: Jan Schampera, prince_jammys, ccsalvesen, others type: snipplet</p> <p>The purpose of this small code collection is to show some code that draws a horizontal line using as less external tools as possible (it's not a big deal to do it with AWK or Perl, but with pure or nearly-pure Bash it gets more interesting).</p> <p>In general, you should be able to use this code to repeat any character or character sequence.</p>"},{"location":"snipplets/print_horizontal_line/#the-simple-way-just-print-it","title":"The simple way: Just print it","text":"<p>Not a miracle, just to be complete here.</p> <pre><code>printf '%s\\n' --------------------\n</code></pre>"},{"location":"snipplets/print_horizontal_line/#the-iterative-way","title":"The iterative way","text":"<p>This one simply loops 20 times, always draws a dash, finally a newline</p> <pre><code>for ((x = 0; x &lt; 20; x++)); do\n printf %s -\ndone\necho\n</code></pre>"},{"location":"snipplets/print_horizontal_line/#the-simple-printf-way","title":"The simple printf way","text":"<p>This one uses the <code>printf</code> command to print an empty field with a minimum field width of 20 characters. The text is padded with spaces, since there is no text, you get 20 spaces. The spaces are then converted to <code>-</code> by the <code>tr</code> command.</p> <pre><code>printf '%20s\\n' | tr ' ' -\n</code></pre> <p>whitout an external command, using the (non-POSIX) substitution expansion and <code>-v</code> option:</p> <pre><code>printf -v res %20s\nprintf '%s\\n' \"${res// /-}\"\n</code></pre>"},{"location":"snipplets/print_horizontal_line/#a-line-across-the-entire-width-of-the-terminal","title":"A line across the entire width of the terminal","text":"<p>This is a variant of the above that uses <code>tput cols</code> to find the width of the terminal and set that number as the minimum field witdh.</p> <pre><code>printf '%*s\\n' \"${COLUMNS:-$(tput cols)}\" '' | tr ' ' -\n</code></pre>"},{"location":"snipplets/print_horizontal_line/#the-more-advanced-printf-way","title":"The more advanced printf way","text":"<p>This one is a bit tricky. The format for the <code>printf</code> command is <code>%.0s</code>, which specified a field with the maximum length of zero. After this field, <code>printf</code> is told to print a dash. You might remember that it's the nature of <code>printf</code> to repeat, if the number of conversion specifications is less than the number of given arguments. With brace expansion <code>{1..20}</code>, 20 arguments are given (you could easily write <code>1 2 3 4 ... 20</code>, of course!). Following happens: The zero-length field plus the dash is repeated 20 times. A zero length field is, naturally, invisible. What you see is the dash, repeated 20 times.</p> <pre><code># Note: you might see that as ''%.s'', which is a (less documented) shorthand for ''%.0s''\nprintf '%.0s-' {1..20}; echo\n</code></pre> <p>If the 20 is variable, you can use eval to insert the expansion (take care that using <code>eval</code> is potentially dangerous if you evaluate external data):</p> <pre><code>eval printf %.0s- '{1..'\"${COLUMNS:-$(tput cols)}\"\\}; echo\n</code></pre> <p>Or restrict the length to 1 and prefix the arguments with the desired character.</p> <pre><code>eval printf %.1s '-{1..'\"${COLUMNS:-$(tput cols)}\"\\}; echo\n</code></pre> <p>You can also do it the crazy ormaaj way\u2122 following basically the same principle as this string reverse example. It completely depends on Bash due to its brace expansion evaluation order and array parameter parsing details. As above, the eval only inserts the COLUMNS expansion into the expression and isn't involved in the rest, other than to put the <code>_</code> value into the environment of the <code>_[0]</code> expansion. This works well since we\\'re not creating one set of arguments and then editing or deleting them to create another as in the previous examples.</p> <pre><code>_=- command eval printf %s '\"${_[0]\"{0..'\"${COLUMNS:-$(tput cols)}\"'}\"}\"'; echo\n</code></pre>"},{"location":"snipplets/print_horizontal_line/#the-parameter-expansion-way","title":"The parameter expansion way","text":"<p>Preparing enough dashes in advance, we can then use a non-POSIX subscript expansion:</p> <pre><code>hr=---------------------------------------------------------------\\\n----------------------------------------------------------------\nprintf '%s\\n' \"${hr:0:${COLUMNS:-$(tput cols)}}\"\n</code></pre> <p>A more flexible approach, and also using modal terminal line-drawing characters instead of hyphens:</p> <pre><code>hr() {\n local start=$'\\e(0' end=$'\\e(B' line='qqqqqqqqqqqqqqqq'\n local cols=${COLUMNS:-$(tput cols)}\n while ((${#line} &lt; cols)); do line+=\"$line\"; done\n printf '%s%s%s\\n' \"$start\" \"${line:0:cols}\" \"$end\"\n}\n</code></pre>"},{"location":"snipplets/print_horizontal_line/#related-articles","title":"Related articles","text":"<ul> <li>printf</li> </ul>"},{"location":"snipplets/rndstr/","title":"Print a random string or select random elements","text":"<p>---- dataentry snipplet ---- snipplet_tags: terminal, line LastUpdate_dt: 2013-04-30 Contributors: Dan Douglas (ormaaj) type: snipplet</p> <p>First off, here is a fast / reliable random string function for scripts or libraries which can optionally assign directly to a variable.</p> <pre><code># Print or assign a random alphanumeric string of a given length.\n# rndstr len [ var ]\nfunction rndstr {\n if [[ $FUNCNAME == \"${FUNCNAME[1]}\" ]]; then\n unset -v a\n printf \"$@\"\n elif [[ $1 != +([[:digit:]]) ]]; then\n return 1\n elif (( $1 )); then\n typeset -a a=({a..z} {A..Z} {0..9})\n eval '${2:+\"$FUNCNAME\" -v} \"${2:-printf}\" -- %s \"${a[RANDOM%'\"${#a[@]}\"']\"{1..'\"$1\"'}\"}\"'\n fi\n}\n</code></pre> <p>This example prints 10 random positional parameters and operates on basically the same principle as the <code>rndstr</code> function above.</p> <pre><code> ~ $ ( set -- foo bar baz bork; printf '%s ' \"${!_[_=RANDOM%$#+1,0]\"{0..10}\"}\"; echo )\nbork bar baz baz foo baz baz baz baz baz bork\n</code></pre> This has some interesting option parsing concepts, but is overly complex. This is a good example of working too hard to avoid an eval for no benefit and some performance penalty. :/ <pre><code># Print or assign a random alphanumeric string of a given length.\n# rndstr [ -v var ] len\n# Bash-only\nrndstr()\n if [[ $FUNCNAME == \"${FUNCNAME[1]}\" ]]; then\n # On recursion, this branch unsets the outer scope's locals and assigns the result.\n unset -v a b\n printf -v \"$1\" %s \"${@:2}\"\n elif ! { [[ $1 == -v ]] &amp;&amp; shift; }; [[ $?+1 -ne $# || ${!#} != +([[:digit:]]) || ( $? -gt 0 &amp;&amp; -z $1 ) ]]; then\n # This branch does input validation, strips -v, and guarantees we're left with either 1 or 2 args.\n return 1\n elif (( ! ${!#} )); then\n # If a zero-length string is requested, return success.\n return\n else\n # This line generates the string and assigns it to \"b\".\n local -a a=({a..z} {A..Z} {0..9}) 'b=(\"${a[RANDOM%'\"${#a[@]}\"']\"{1..'\"${!#}\"'}\"}\")'\n if (( $# == 2 )); then\n # If -v, then pass a variable name and value to assign and recurse once.\n \"$FUNCNAME\" \"$1\" \"${b[@]}\"\n else\n # If no -v, write to stdout.\n printf %s \"${b[@]}\"\n fi\n fi\n</code></pre> <p>The remaining examples don't use quite the same tricks, which will hopefully be explained elsewhere eventually. See unset for why doing assignments in this way works well.</p> <p>This next example is a variation on print_horizontal_line. We\\'re using the printf field width specifier to truncate the values of a <code>sequence expansion</code> to one character.</p> <pre><code>a=({a..z} {A..Z} {0..9})\nprintf '%.1s' \"${a[RANDOM%${#a[@]}]}\"{0..9} $'\\n'\n</code></pre> <p>The extra detail that makes this work is to notice that in Bash, brace expansion is usually the very first type of expansion to be processed, always before parameter expansion. Bash is unique in this respect -- all other shells with a brace expansion feature perform it almost last, just before pathname expansion. First the sequence expansion generates ten parameters, then the parameters are expanded left-to-right causing the arithmetic for each to be evaluated individually, resulting in independent selection of random element of <code>a</code>. To get ten of the same element, put the array selection inside the format string where it will only be evaluated once, just like the dashed-line trick:</p> <pre><code>printf \"%.s${a[RANDOM%${#a[@]}]}\" {0..9} \n</code></pre> <p>Selecting random elements whose lengths are not fixed is harder.</p> <pre><code>a=(one two three four five six seven eight nine ten)\nprintf '%.*s ' $(printf '%s ' \"${#a[x=RANDOM%${#a[@]}]} ${a[x]}\"{1..10})\n</code></pre> <p>This generates each parameter and it's length in pairs. The \\'*\\' modifier instructs printf to use the value preceding each parameter as the field width. Note the space between the parameters. This example unfortunately relies upon the unquoted command substitution to perform unsafe wordsplitting so that the outer printf gets each argument. Values in the array can't contain characters in IFS, or anything that might be interpreted as a pattern without using <code>set -f</code>.</p> <p>Lastly, empty brace expansions can be used which don't generate any output that would need to be filtered. The disadvantage of course is that you must construct the brace expansion syntax to add up to the number of arguments to be generated, where the most optimal solution is its set of prime factors.</p> <pre><code>a=(one two three)\necho \"${a[RANDOM%${#a[@]}]}\"{,}{,,,,}\n</code></pre>"},{"location":"snipplets/screen_saverestore/","title":"Save and restore terminal/screen content","text":"<p>---- dataentry snipplet ---- snipplet_tags: terminal, restore screen LastUpdate_dt: 2010-07-31 Contributors: Greg Wooledge type: snipplet</p> <p>This cool hack uses the terminal capabilities (see <code>terminfo(5)</code> manual) smcup and rmcup to save and restore the terminal content.</p> <p>For sure, you've already seen those programs that restore the terminal contents after they did their work (like <code>vim</code>).</p> <pre><code># save, clear screen\ntput smcup\nclear\n\n# example \"application\" follows...\nread -n1 -p \"Press any key to continue...\"\n# example \"application\" ends here\n\n# restore\ntput rmcup\n</code></pre>"},{"location":"snipplets/ssh_fetchkeys/","title":"Fetching SSH hostkeys without interaction","text":"<p>---- dataentry snipplet ---- snipplet_tags: ssh, ssh-keys LastUpdate_dt: 2010-07-31 Contributors: Jan Schampera</p> <p>Applies at least to <code>openssh</code>.</p> <p>To get the hostkeys for a server, and write them to <code>known_hosts</code>-file (to avoid that yes/no query when the key isn't known), you can do:</p> <pre><code>ssh-keyscan -t rsa foo foo.example.com 1.2.3.4 &gt;&gt; ~/.ssh/known_host\n</code></pre> <p>This example queries the hostkeys for the very same machine, but under 3 different \\\"names\\\" (hostname, FQDN, IP) and redirects the output to the <code>known_hosts</code>-file.</p> <p>Notes:</p> <ul> <li>if done blindly, the <code>known_host</code>-file may grow very large. It might be wise to check for key existance first</li> <li>if multiple keys for the same host exist in <code>known_hosts</code>, the first one is taken (which might be an old or wrong one)</li> </ul>"},{"location":"snipplets/ssh_local_var/","title":"Run some bash commands with SSH remotely using local variables","text":"<p>---- dataentry snipplet ---- snipplet_tags: ssh, variables LastUpdate_dt: 2010-07-31 Contributors: cweiss type: snipplet</p> <p>In this example, we want to make sure a certain file exists on the remote server:</p> <pre><code>file=/tmp/file.log\nssh ${options} ${login} \"if [ ! -e '$file' ] ; then touch '$file' ; fi\"\n</code></pre> <p>Notice the command is surrounded by double quotes, and the \\$file variable is surrounded by single quotes. That has the effect to be wordsplit-proof in the local shell (due to the double-quotes) and in the remote shell (due to the single-quotes).</p>"},{"location":"snipplets/wrapperargs/","title":"Generate code with own arguments properly quoted","text":"<p>There are situations where Bash code needs to generate Bash code. A script that writes out another script the user or cron may start, for example.</p> <p>The general issue is easy, just write out text to the file.</p> <p>A specific detail of it is tricky: If the generated script needs to call a command using the arguments the first original script got, you have problem in writing out the correct code.</p> <p>I.e. if you run your generator script like</p> <pre><code>./myscript \"give me 'some' water\"\n</code></pre> <p>then this script should generate code that looks like</p> <pre><code>echo give me 'some' water\"\n</code></pre> <p>you need correct escapes or quotes to not generate shell special characters out of normal text (like embedded dollar signs <code>$</code>).</p> <p>Solution:</p> <p>A loop over the own arguments that writes out properly quoted/escaped code to the generated script file</p> <p>There are two (maybe more) easy options:</p> <ul> <li>writing out singlequoted strings and handle the embedded singlequotes</li> <li>the printf command knows the <code>%q</code> format specification, which will print a string (like <code>%s</code> does), but with all shell special characters escaped</li> </ul>","tags":["arguments","quoting","escape","quote","wrapper","generate"]},{"location":"snipplets/wrapperargs/#using-singlequoted-string","title":"Using singlequoted string","text":"<pre><code>#!/bin/bash\n\n# first option:\n# generate singlequoted strings out of your own arguments and handle embedded singlequotes\n# here to call 'echo' in the generated script\n\n{\nprintf \"#!/bin/bash\\n\\n\"\nprintf \"echo \"\nfor arg; do\n arg=${arg/\\'/\\'\\\\\\'\\'}\n printf \"'%s' \" \"${arg}\"\ndone\n\nprintf \"\\n\"\n} &gt;s2\n</code></pre> <p>The generated script will look like:</p> <pre><code>#!/bin/bash\n\necho 'fir$t' 'seco \"ond\"' 'thir'\\''d'\n</code></pre>","tags":["arguments","quoting","escape","quote","wrapper","generate"]},{"location":"snipplets/wrapperargs/#using-printf","title":"Using printf","text":"<p>The second method is easier, though more or less Bash-only (due to the <code>%q</code> in printf):</p> <pre><code>#!/bin/bash\n\n{\nprintf \"#!/bin/bash\\n\\n\"\nprintf \"echo \"\nfor arg; do\n printf '%q ' \"$arg\"\ndone\n\nprintf \"\\n\"\n} &gt;s2\n</code></pre> <p>The generated script will look like:</p> <pre><code>#!/bin/bash\n\necho fir\\$t seco\\ \\\"ond\\\" thir\\'d\n</code></pre>","tags":["arguments","quoting","escape","quote","wrapper","generate"]},{"location":"snipplets/xclip/","title":"X-Clipboard on Commandline","text":"<p>---- dataentry snipplet ---- snipplet_tags: clipboard, x11, xclip, readline LastUpdate_dt: 2010-07-31 Contributors: Josh Triplett type: snipplet</p> <pre><code># Make Control-v paste, if in X and if xclip available - Josh Triplett\nif [ -n \"$DISPLAY\" ] &amp;&amp; [ -x /usr/bin/xclip ] ; then\n # Work around a bash bug: \\C-@ does not work in a key binding\n bind '\"\\C-x\\C-m\": set-mark'\n # The '#' characters ensure that kill commands have text to work on; if\n # not, this binding would malfunction at the start or end of a line.\n bind 'Control-v: \"#\\C-b\\C-k#\\C-x\\C-?\\\"$(xclip -o -selection c)\\\"\\e\\C-e\\C-x\\C-m\\C-a\\C-y\\C-?\\C-e\\C-y\\ey\\C-x\\C-x\\C-d\"'\nfi\n</code></pre> <p>The behaviour is a bit tricky to explain:</p> <ul> <li>kill text after the cursor<ul> <li>since the kill command wants text, it blindly adds a fake text \\\"#\\\" here</li> </ul> </li> <li>kill text before the cursor<ul> <li>since the kill command wants text, it blindly adds a fake text \\\"#\\\" here, too</li> </ul> </li> <li>write out <code>\"$(xclip -o -selection c)\"</code></li> <li>run Control-Meta-e (shell-expand-line) to expand the <code>\"$(xclip -o -selection c)\"</code></li> <li>yank the previously killed text back where it belongs</li> </ul> <p>Of course you can use any other command, you\\'re not limited to <code>xclip</code> here.</p> <p>Note: C-@ as well as M-SPC both works and set the mark for me -- pgas</p>"},{"location":"syntax/arith_expr/","title":"Arithmetic expressions","text":"<p>Arithmetic expressions are used in several situations:</p> <ul> <li>arithmetic evaluation command</li> <li>arithmetic expansion</li> <li>substring parameter expansion</li> <li>the <code>let</code> builtin command</li> <li>C-style for loop</li> <li>array indexing</li> <li>conditional expressions</li> <li>Assignment statements, and arguments to declaration commands of variables with the integer attribute.</li> </ul> <p>These expressions are evaluated following some rules described below. The operators and rules of arithmetic expressions are mainly derived from the C programming language.</p> <p>This article describes the theory of the used syntax and the behaviour. To get practical examples without big explanations, see this page on Greg's wiki.</p>","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#constants","title":"Constants","text":"<p>Mathematical constants are simply fixed values you write: <code>1</code>, <code>3567</code>, or <code>4326</code>. Bash interprets some notations specially:</p> <ul> <li><code>0...</code> (leading zero) is interpreted as an octal value</li> <li><code>0x...</code> is interpreted as a hex value</li> <li><code>0X...</code> also interpreted as a hex</li> <li><code>&lt;BASE&gt;#...</code> is interpreted as a number according to the specified base <code>&lt;BASE&gt;</code>, e.g., <code>2#00111011</code> (see below)</li> </ul> <p>If you have a constant set in a variable, like,</p> <pre><code>x=03254\n</code></pre> <p>this is interpreted as an octal value. If you want it to be interpreted as a decimal value, you need to expand the parameter and specify base 10:</p> <pre><code># this is interpreted as a decimal:\necho $(( 10#$x ))\n\n# this is interpreted as an octal:\necho $(( x ))\n\n# this is an invalid digit for base 10 (the \"x\")...:\necho $(( 10#x ))\n</code></pre>","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#different-bases","title":"Different bases","text":"<p>For a constant, the base can be specified using the form</p> <pre><code>&lt;BASE&gt;#&lt;DIGITS...&gt;\n</code></pre> <p>Regardless of the specified base, the arithmetic expressions will, if ever displayed, be displayed in decimal!</p> <p>When no base is specified, the base 10 (decimal) is assumed, except when the prefixes as mentioned above (octals, hexadecimals) are present. The specified base can range from 2 to 64. To represent digits in a specified base greater than 10, characters other than 0 to 9 are needed (in this order, low =&gt; high):</p> <ul> <li><code>0 ... 9</code></li> <li><code>a ... z</code></li> <li><code>A ... Z</code></li> <li><code>@</code></li> <li><code>_</code></li> </ul> <p>Let's quickly invent a new number system with base 43 to show what I mean:</p> <pre><code>$ echo $((43#1))\n1\n\n$ echo $((43#a))\n10\n\n$echo $((43#A))\n36\n\n$ echo $((43#G))\n42\n\n$ echo $((43#H))\nbash: 43#H: value too great for base (error token is \"43#H\")\n</code></pre> <p>If you have no clue what a base is and why there might be other bases, and what numbers are and how they are built, then you don't need different bases.</p> <p>If you want to convert between the usual bases (octal, decimal, hex), use the printf command and its format strings.</p>","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#shell-variables","title":"Shell variables","text":"<p>Shell variables can of course be used as operands, even when the integer attribute is not turned on (by <code>declare -i &lt;NAME&gt;</code>). If the variable is empty (null) or unset, its reference evaluates to 0. If the variable doesn't hold a value that looks like a valid expression (numbers or operations), the expression is re-used to reference, for example, the named parameters, e.g.:</p> <pre><code>test=string\nstring=3\n\necho $((test))\n# will output \"3\"!\n</code></pre> <p>Of course, in the end, when it finally evaluates to something that is not a valid arithmetic expression (newlines, ordinary text, ...) then you'll get an error.</p> <p>When variables are referenced, the notation <code>1 + $X</code> is equivalent to the notation <code>1 + X</code>, both are allowed.</p> <p>When variables are referenced like <code>$X</code>, the rules of parameter expansion apply and are performed before the expression is evaluated. Thus, a construct like <code>${MYSTRING:4:3}</code> is valid inside an arithmetic expression.</p>","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#truth","title":"Truth","text":"<p>Unlike command exit and return codes, arithmetic expressions evaluate to logical \"true\" when they are not 0. When they are 0, they evaluate to \"false\". The arithmetic evaluation compound command reverses the \"truth\" of an arithmetic expression to match the \"truth\" of command exit codes:</p> <ul> <li>if the arithmetic expression brings up a value not 0 (arithmetic true), it returns 0 (shell true)</li> <li>if the arithmetic expression evaluates to 0 (arithmetic false), it returns 1 (shell false)</li> </ul> <p>That means, the following <code>if</code>-clause will execute the <code>else</code>-thread:</p> <pre><code>if ((0)); then\n echo \"true\"\nelse\n echo \"false\"\nfi\n</code></pre>","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#operators","title":"Operators","text":"","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#assignment","title":"Assignment","text":"Operator Description <code>&lt;ID&gt; = &lt;EXPR&gt;</code> normal assignment <code>&lt;ID&gt; *= &lt;EXPR&gt;</code> equivalent to <code>&lt;ID&gt; = &lt;ID&gt; * &lt;EXPR&gt;</code>, see calculation operators <code>&lt;ID&gt; /= &lt;EXPR&gt;</code> equivalent to <code>&lt;ID&gt; = &lt;ID&gt; / &lt;EXPR&gt;</code>, see calculation operators <code>&lt;ID&gt; %= &lt;EXPR&gt;</code> equivalent to <code>&lt;ID&gt; = &lt;ID&gt; % &lt;EXPR&gt;</code>, see calculation operators <code>&lt;ID&gt; += &lt;EXPR&gt;</code> equivalent to <code>&lt;ID&gt; = &lt;ID&gt; + &lt;EXPR&gt;</code>, see calculation operators <code>&lt;ID&gt; -= &lt;EXPR&gt;</code> equivalent to <code>&lt;ID&gt; = &lt;ID&gt; - &lt;EXPR&gt;</code>, see calculation operators <code>&lt;ID&gt; &lt;&lt;= &lt;NUMBER&gt;</code> equivalent to <code>&lt;ID&gt; = &lt;ID&gt; &lt;&lt; &lt;NUMBER&gt;</code>, see bit operations <code>&lt;ID&gt; &gt;&gt;= &lt;NUMBER&gt;</code> equivalent to <code>&lt;ID&gt; = &lt;ID&gt; &gt;&gt; &lt;NUMBER&gt;</code>, see bit operations <code>&lt;ID&gt; &amp;= &lt;EXPR&gt;</code> equivalent to <code>&lt;ID&gt; = &lt;ID&gt; &amp; &lt;EXPR&gt;</code>, see bit operations <code>&lt;ID&gt; ^= &lt;EXPR&gt;</code> equivalent to <code>&lt;ID&gt; = &lt;ID&gt; ^ &lt;EXPR&gt;</code>, see bit operations <code>&lt;ID&gt;|= &lt;EXPR&gt;</code> equivalent to <code>&lt;ID&gt; = &lt;ID&gt;|&lt;EXPR&gt;</code>, see bit operations","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#calculations","title":"Calculations","text":"Operator Description <code>*</code> multiplication <code>/</code> division <code>%</code> remainder (modulo) <code>+</code> addition <code>-</code> subtraction <code>**</code> exponentiation","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#comparisons","title":"Comparisons","text":"Operator Description <code>&lt;</code> comparison: less than <code>&gt;</code> comparison: greater than <code>&lt;=</code> comparison: less than or equal <code>&gt;=</code> comparison: greater than or equal <code>==</code> equality <code>!=</code> inequality","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#bit-operations","title":"Bit operations","text":"Operator Description <code>~</code> bitwise negation <code>&lt;&lt;</code> bitwise shifting (left) <code>&gt;&gt;</code> bitwise shifting (right) <code>&amp;</code> bitwise AND <code>^</code> bitwise exclusive OR (XOR) <code>|</code> bitwise OR","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#logical","title":"Logical","text":"Operator Description <code>!</code> logical negation <code>&amp;&amp;</code> logical AND <code>||</code> logical OR","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#misc","title":"Misc","text":"Operator Description <code>id++</code> post-increment of the variable <code>id</code> (not required by POSIX\u00ae) <code>id--</code> post-decrement of the variable <code>id</code> (not required by POSIX\u00ae) <code>++id</code> pre-increment of the variable <code>id</code> (not required by POSIX\u00ae) <code>--id</code> pre-decrement of the variable <code>id</code> (not required by POSIX\u00ae) <code>+</code> unary plus <code>-</code> unary minus <code>&lt;EXPR&gt; ? &lt;EXPR&gt; : &lt;EXPR&gt;</code> conditional (ternary) operator &lt;condition&gt; ? &lt;result-if-true&gt; : &lt;result-if-false&gt; <code>&lt;EXPR&gt; , &lt;EXPR&gt;</code> expression list <code>( &lt;EXPR&gt; )</code> subexpression (to force precedence)","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#precedence","title":"Precedence","text":"<p>The operator precedence is as follows (highest -&gt; lowest):</p> <ul> <li>Postfix (<code>id++</code>, <code>id--</code>)</li> <li>Prefix (<code>++id</code>, <code>--id</code>)</li> <li>Unary minus and plus (<code>-</code>, <code>+</code>)</li> <li>Logical and bitwise negation (<code>!</code>, <code>~</code>)</li> <li>Exponentiation (<code>**</code>)</li> <li>Multiplication, division, remainder (<code>*</code>, <code>/</code>, <code>%</code>)</li> <li>Addition, subtraction (<code>+</code>, <code>-</code>)</li> <li>Bitwise shifts (<code>&lt;&lt;</code>, <code>&gt;&gt;</code>)</li> <li>Comparison (<code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code>)</li> <li>(In-)equality (<code>==</code>, <code>!=</code>)</li> <li>Bitwise AND (<code>&amp;</code>)</li> <li>Bitwise XOR (<code>^</code>)</li> <li>Bitwise OR (<code>|</code>)</li> <li>Logical AND (<code>&amp;&amp;</code>)</li> <li>Logical OR (<code>||</code>)</li> <li>Ternary operator (<code>&lt;EXPR&gt; ? &lt;EXPR&gt; : &lt;EXPR&gt;</code>)</li> <li>Assignments (<code>=</code>, <code>*=</code>, <code>/=</code>, <code>%=</code>, <code>+=</code>, <code>-=</code>, <code>&lt;&lt;=</code>, <code>&gt;&gt;=</code>, <code>&amp;=</code>, <code>^=</code>, <code>|=</code>)</li> <li>Expression list operator (<code>&lt;EXPR&gt; , &lt;EXPR&gt;</code>)</li> </ul> <p>The precedence can be adjusted using subexpressions of the form <code>( &lt;EXPR&gt; )</code> at any time. These subexpressions are always evaluated first.</p>","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#arithmetic-expressions-and-return-codes","title":"Arithmetic expressions and return codes","text":"<p>Bash's overall language construct is based on exit codes or return codes of commands or functions to be executed. <code>if</code> statements, <code>while</code> loops, etc., they all take the return codes of commands as conditions.</p> <p>Now the problem is: The return codes (0 means \"TRUE\" or \"SUCCESS\", not 0 means \"FALSE\" or \"FAILURE\") don't correspond to the meaning of the result of an arithmetic expression (0 means \"FALSE\", not 0 means \"TRUE\").</p> <p>That's why all commands and keywords that do arithmetic operations attempt to translate the arithmetical meaning into an equivalent return code. This simply means:</p> <ul> <li>if the arithmetic operation evaluates to 0 (\"FALSE\"), the return code is not 0 (\"FAILURE\")</li> <li>if the arithmetic operation evaluates to 1 (\"TRUE\"), the return code is 0 (\"SUCCESS\")</li> </ul> <p>This way, you can easily use arithmetic expressions (along with the commands or keywords that operate them) as conditions for <code>if</code>, <code>while</code> and all the others, including <code>set -e</code> for autoexit on error:</p> <pre><code>MY_TEST_FLAG=0\n\nif ((MY_TEST_FLAG)); then\n echo \"MY_TEST_FLAG is ON\"\nelse\n echo \"MY_TEST_FLAG is OFF\"\nfi\n</code></pre> <p>Beware that <code>set -e</code> can change the runtime behavior of scripts.</p> <p>For example,</p> <p>This non-equivalence of code behavior deserves some attention. Consider what happens if v happens to be zero in the expression below:</p> <pre><code>((v += 0))\necho $?\n</code></pre> <p>1</p> <p>(\"FAILURE\")</p> <pre><code>v=$((v + 0))\necho $?\n</code></pre> <p>0</p> <p>(\"SUCCESS\")</p> <p>The return code behavior is not equivalent to the arithmetic behavior, as has been noted.</p> <p>A workaround is to use a list operation that returns True, or use the second assignment style.</p> <pre><code>((v += 0)) || :\necho $?\n</code></pre> <p>0</p> <p>(\"SUCCESS\")</p> <p>This change in code behavior was discovered once the script was run under set -e.</p>","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arith_expr/#arithmetic-expressions-in-bash","title":"Arithmetic expressions in Bash","text":"<ul> <li>The C-style for-loop</li> <li>Arithmetic expansion</li> <li>Arithmetic evaluation compound command</li> <li>The \"let\" builtin command</li> </ul>","tags":["bash","shell","scripting","math","arithmetic","C","calculation","integer"]},{"location":"syntax/arrays/","title":"Arrays","text":""},{"location":"syntax/arrays/#purpose","title":"Purpose","text":"<p>An array is a parameter that holds mappings from keys to values. Arrays are used to store a collection of parameters into a parameter. Arrays (in any programming language) are a useful and common composite data structure, and one of the most important scripting features in Bash and other shells.</p> <p>Here is an abstract representation of an array named <code>NAMES</code>. The indexes go from 0 to 3.</p> <pre><code>NAMES\n 0: Peter\n 1: Anna\n 2: Greg\n 3: Jan\n</code></pre> <p>Instead of using 4 separate variables, multiple related variables are grouped grouped together into elements of the array, accessible by their key. If you want the second name, ask for index 1 of the array <code>NAMES</code>.</p>"},{"location":"syntax/arrays/#indexing","title":"Indexing","text":"<p>Bash supports two different types of ksh-like one-dimensional arrays. Multidimensional arrays are not implemented.</p> <ul> <li>Indexed arrays use positive integer numbers as keys. Indexed arrays are always sparse, meaning indexes are not necessarily contiguous. All syntax used for both assigning and dereferencing indexed arrays is an arithmetic evaluation context (see #Referencing). As in C and many other languages, the numerical array indexes start at 0 (zero). Indexed arrays are the most common, useful, and portable type. Indexed arrays were first introduced to Bourne-like shells by ksh88. Similar, partially compatible syntax was inherited by many derivatives including Bash. Indexed arrays always carry the <code>-a</code> attribute.</li> <li>Associative arrays (sometimes known as a \"hash\" or \"dict\") use arbitrary nonempty strings as keys. In other words, associative arrays allow you to look up a value from a table based upon its corresponding string label. Associative arrays are always unordered, they merely associate key-value pairs. If you retrieve multiple values from the array at once, you can't count on them coming out in the same order you put them in. Associative arrays always carry the <code>-A</code> attribute, and unlike indexed arrays, Bash requires that they always be declared explicitly (as indexed arrays are the default, see declaration). Associative arrays were first introduced in ksh93, and similar mechanisms were later adopted by Zsh and Bash version 4. These three are currently the only POSIX-compatible shells with any associative array support.</li> </ul>"},{"location":"syntax/arrays/#syntax","title":"Syntax","text":""},{"location":"syntax/arrays/#referencing","title":"Referencing","text":"<p>To accommodate referring to array variables and their individual elements, Bash extends the parameter naming scheme with a subscript suffix. Any valid ordinary scalar parameter name is also a valid array name: <code>[[:alpha:]_][[:alnum:]_]*</code>. The parameter name may be followed by an optional subscript enclosed in square brackets to refer to a member of the array.</p> <p>The overall syntax is <code>arrname[subscript]</code> - where for indexed arrays, <code>subscript</code> is any valid arithmetic expression, and for associative arrays, any nonempty string. Subscripts are first processed for parameter and arithmetic expansions, and command and process substitutions. When used within parameter expansions or as an argument to the unset builtin, the special subscripts <code>*</code> and <code>@</code> are also accepted which act upon arrays analogously to the way the <code>@</code> and <code>*</code> special parameters act upon the positional parameters. In parsing the subscript, bash ignores any text that follows the closing bracket up to the end of the parameter name.</p> <p>With few exceptions, names of this form may be used anywhere ordinary parameter names are valid, such as within arithmetic expressions, parameter expansions, and as arguments to builtins that accept parameter names. An array is a Bash parameter that has been given the <code>-a</code> (for indexed) or <code>-A</code> (for associative) attributes. However, any regular (non-special or positional) parameter may be validly referenced using a subscript, because in most contexts, referring to the zeroth element of an array is synonymous with referring to the array name without a subscript.</p> <pre><code># \"x\" is an ordinary non-array parameter.\n$ x=hi; printf '%s ' \"$x\" \"${x[0]}\"; echo \"${_[0]}\"\nhi hi hi\n</code></pre> <p>The only exceptions to this rule are in a few cases where the array variable's name refers to the array as a whole. This is the case for the <code>unset</code> builtin (see destruction) and when declaring an array without assigning any values (see declaration).</p>"},{"location":"syntax/arrays/#declaration","title":"Declaration","text":"<p>The following explicitly give variables array attributes, making them arrays:</p> Syntax Description <code>ARRAY=()</code> Declares an indexed array <code>ARRAY</code> and initializes it to be empty. This can also be used to empty an existing array. <code>ARRAY[0]=</code> Generally sets the first element of an indexed array. If no array <code>ARRAY</code> existed before, it is created. <code>declare -a ARRAY</code> Declares an indexed array <code>ARRAY</code>. An existing array is not initialized. <code>declare -A ARRAY</code> Declares an associative array <code>ARRAY</code>. This is the one and only way to create associative arrays. <p>As an example, and for use below, let's declare our <code>NAMES</code> array as described above:</p> <pre><code> declare -a NAMES=('Peter' 'Anna' 'Greg' 'Jan')\n</code></pre>"},{"location":"syntax/arrays/#storing-values","title":"Storing values","text":"<p>Storing values in arrays is quite as simple as storing values in normal variables.</p> Syntax Description <code>ARRAY[N]=VALUE</code> Sets the element <code>N</code> of the indexed array <code>ARRAY</code> to <code>VALUE</code>. <code>N</code> can be any valid arithmetic expression. <code>ARRAY[STRING]=VALUE</code> Sets the element indexed by <code>STRING</code> of the associative array <code>ARRAY</code>. <code>ARRAY=VALUE</code> As above. If no index is given, as a default the zeroth element is set to <code>VALUE</code>. Careful, this is even true of associative arrays - there is no error if no key is specified, and the value is assigned to string index \"0\". <code>ARRAY=(E1\\ E2\\ ...)</code> Compound array assignment - sets the whole array <code>ARRAY</code> to the given list of elements indexed sequentially starting at zero. The array is unset before assignment unless the += operator is used. When the list is empty (<code>ARRAY=()</code>), the array will be set to an empty array. This method obviously does not use explicit indexes. An associative array can not be set like that! Clearing an associative array using <code>ARRAY=()</code> works. <code>ARRAY=([X]=E1\\ [Y]=E2\\ ...)</code> Compound assignment for indexed arrays with index-value pairs declared individually (here for example <code>X</code> and <code>Y</code>). X and Y are arithmetic expressions. This syntax can be combined with the above - elements declared without an explicitly specified index are assigned sequentially starting at either the last element with an explicit index, or zero. <code>ARRAY=([S1]=E1\\ [S2]=E2\\ ...)</code> Individual mass-setting for associative arrays. The named indexes (here: <code>S1</code> and <code>S2</code>) are strings. <code>ARRAY+=(E1\\ E2\\ ...)</code> Append to ARRAY. <code>ARRAY=(\"${ANOTHER_ARRAY[@]}\")</code> Copy ANOTHER_ARRAY to ARRAY, copying each element. <p>As of now, arrays can't be exported.</p>"},{"location":"syntax/arrays/#getting-values","title":"Getting values","text":"<p>For completeness and details on several parameter expansion variants, see the article about parameter expansion and check the notes about arrays.</p> Syntax Description <code>${ARRAY[N]}</code> Expands to the value of the index <code>N</code> in the indexed array <code>ARRAY</code>. If <code>N</code> is a negative number, it's treated as the offset from the maximum assigned index (can't be used for assignment) - 1 <code>${ARRAY[S]}</code> Expands to the value of the index <code>S</code> in the associative array <code>ARRAY</code>. <code>\"${ARRAY[@]}\" ${ARRAY[@]} \"${ARRAY[*]}\" ${ARRAY[*]}</code> Similar to mass-expanding positional parameters, this expands to all elements. If unquoted, both subscripts <code>*</code> and <code>@</code> expand to the same result, if quoted, <code>@</code> expands to all elements individually quoted, <code>*</code> expands to all elements quoted as a whole. <code>\"${ARRAY[@]:N:M}\" ${ARRAY[@]:N:M} \"${ARRAY[*]:N:M}\" ${ARRAY[*]:N:M}</code> Similar to what this syntax does for the characters of a single string when doing substring expansion, this expands to <code>M</code> elements starting with element <code>N</code>. This way you can mass-expand individual indexes. The rules for quoting and the subscripts <code>*</code> and <code>@</code> are the same as above for the other mass-expansions. <p>For clarification: When you use the subscripts <code>@</code> or <code>*</code> for mass-expanding, then the behaviour is exactly what it is for <code>$@</code> and <code>$*</code> when mass-expanding the positional parameters. You should read this article to understand what's going on.</p>"},{"location":"syntax/arrays/#metadata","title":"Metadata","text":"Syntax Description <code>${#ARRAY[N]}</code> Expands to the length of an individual array member at index <code>N</code> (stringlength) <code>${#ARRAY[STRING]}</code> Expands to the length of an individual associative array member at index <code>STRING</code> (stringlength) <code>${#ARRAY[@]}</code> \\ <code>${#ARRAY[*]}</code> Expands to the number of elements in <code>ARRAY</code> <code>${!ARRAY[@]}</code> \\ <code>${!ARRAY[*]}</code> Expands to the indexes in <code>ARRAY</code> since BASH 3.0"},{"location":"syntax/arrays/#destruction","title":"Destruction","text":"<p>The unset builtin command is used to destroy (unset) arrays or individual elements of arrays.</p> Syntax Description <code>unset -v ARRAY</code> \\ <code>unset -v ARRAY[@]</code> \\ <code>unset -v ARRAY[*]</code> Destroys a complete array <code>unset -v ARRAY[N]</code> Destroys the array element at index <code>N</code> <code>unset -v ARRAY[STRING]</code> Destroys the array element of the associative array at index <code>STRING</code> <p>It is best to explicitly specify -v when unsetting variables with unset.</p> <p>warning</p> <p>Specifying unquoted array elements as arguments to any command, such as with the syntax above may cause pathname expansion to occur due to the presence of glob characters.</p> <p>Example: You are in a directory with a file named <code>x1</code>, and you want to destroy an array element <code>x[1]</code>, with</p> <pre><code>unset x[1]\n</code></pre> <p>then pathname expansion will expand to the filename <code>x1</code> and break your processing!</p> <p>Even worse, if <code>nullglob</code> is set, your array/index will disappear.</p> <p>To avoid this, always quote the array name and index:</p> <pre><code>unset -v 'x[1]'\n</code></pre> <p>This applies generally to all commands which take variable names as arguments. Single quotes preferred.</p>"},{"location":"syntax/arrays/#usage","title":"Usage","text":""},{"location":"syntax/arrays/#numerical-index","title":"Numerical Index","text":"<p>Numerical indexed arrays are easy to understand and easy to use. The Purpose and Indexing chapters above more or less explain all the needed background theory.</p> <p>Now, some examples and comments for you.</p> <p>Let's say we have an array <code>sentence</code> which is initialized as follows:</p> <pre><code>sentence=(Be liberal in what you accept, and conservative in what you send)\n</code></pre> <p>Since no special code is there to prevent word splitting (no quotes), every word there will be assigned to an individual array element. When you count the words you see, you should get 12. Now let's see if Bash has the same opinion:</p> <pre><code>$ echo ${#sentence[@]}\n12\n</code></pre> <p>Yes, 12. Fine. You can take this number to walk through the array. Just subtract 1 from the number of elements, and start your walk at 0 (zero):</p> <pre><code>((n_elements=${#sentence[@]}, max_index=n_elements - 1))\n\nfor ((i = 0; i &lt;= max_index; i++)); do\n echo \"Element $i: '${sentence[i]}'\"\ndone\n</code></pre> <p>You always have to remember that, it seems newbies have problems sometimes. Please understand that numerical array indexing begins at 0 (zero)!</p> <p>The method above, walking through an array by just knowing its number of elements, only works for arrays where all elements are set, of course. If one element in the middle is removed, then the calculation is nonsense, because the number of elements doesn't correspond to the highest used index anymore (we call them \"sparse arrays\").</p> <p>Now, suppose that you want to replace your array <code>sentence</code> with the values in the previously-declared array <code>NAMES</code> . You might think you could just do</p> <pre><code>$ unset sentence ; declare -a sentence=NAMES\n$ echo ${#sentence[@]}\n1\n# omit calculating max_index as above, and iterate as one-liner\n$ for ((i = 0; i &lt; ${#sentence[@]}; i++)); do echo \"Element $i: '${sentence[i]}'\" ; done\nElement 0: 'NAMES'\n</code></pre> <p>Obviously that's wrong. What about</p> <pre><code>$ unset sentence ; declare -a sentence=${NAMES}\n</code></pre> <p>? Again, wrong:</p> <pre><code>$ echo ${#sentence[*]}\n1\n$ for ((i = 0; i &lt; ${#sentence[@]}; i++)); do echo \"Element $i: '${sentence[i]}'\" ; done\nElement 0: 'Peter'\n</code></pre> <p>So what's the right way? The (slightly ugly) answer is, reuse the enumeration syntax:</p> <pre><code>$ unset sentence ; declare -a sentence=(\"${NAMES[@]}\")\n$ echo ${#sentence[@]}\n4\n$ for ((i = 0; i &lt; ${#sentence[@]}; i++)); do echo \"Element $i: '${sentence[i]}'\" ; done\nElement 0: 'Peter'\nElement 1: 'Anna'\nElement 2: 'Greg'\nElement 3: 'Jan'\n</code></pre>"},{"location":"syntax/arrays/#associative-bash-4","title":"Associative (Bash 4)","text":"<p>Associative arrays (or hash tables) are not much more complicated than numerical indexed arrays. The numerical index value (in Bash a number starting at zero) just is replaced with an arbitrary string:</p> <pre><code># declare -A, introduced with Bash 4 to declare an associative array\ndeclare -A sentence\n\nsentence[Begin]='Be liberal in what'\nsentence[Middle]='you accept, and conservative'\nsentence[End]='in what you send'\nsentence['Very end']=...\n</code></pre> <p>Beware: don't rely on the fact that the elements are ordered in memory like they were declared, it could look like this:</p> <pre><code># output from 'set' command\nsentence=([End]=\"in what you send\" [Middle]=\"you accept, and conservative \" [Begin]=\"Be liberal in what \" [\"Very end\"]=\"...\")\n</code></pre> <p>This effectively means, you can get the data back with <code>\"${sentence[@]}\"</code>, of course (just like with numerical indexing), but you can't rely on a specific order. If you want to store ordered data, or re-order data, go with numerical indexes. For associative arrays, you usually query known index values:</p> <pre><code>for element in Begin Middle End \"Very end\"; do\n printf \"%s\" \"${sentence[$element]}\"\ndone\nprintf \"\\n\"\n</code></pre> <p>A nice code example: Checking for duplicate files using an associative array indexed with the SHA sum of the files:</p> <pre><code># Thanks to Tramp in #bash for the idea and the code\n\nunset flist; declare -A flist;\nwhile read -r sum fname; do\n if [[ ${flist[$sum]} ]]; then\n printf 'rm -- \"%s\" # Same as &gt;%s&lt;\\n' \"$fname\" \"${flist[$sum]}\"\n else\n flist[$sum]=\"$fname\"\n fi\ndone &lt; &lt;(find . -type f -exec sha256sum {} +) &gt;rmdups\n</code></pre>"},{"location":"syntax/arrays/#integer-arrays","title":"Integer arrays","text":"<p>Any type attributes applied to an array apply to all elements of the array. If the integer attribute is set for either indexed or associative arrays, then values are considered as arithmetic for both compound and ordinary assignment, and the += operator is modified in the same way as for ordinary integer variables.</p> <pre><code> ~ $ ( declare -ia 'a=(2+4 [2]=2+2 [a[2]]=\"a[2]\")' 'a+=(42 [a[4]]+=3)'; declare -p a )\ndeclare -ai a='([0]=\"6\" [2]=\"4\" [4]=\"7\" [5]=\"42\")'\n</code></pre> <p><code>a[0]</code> is assigned to the result of <code>2+4</code>. <code>a[2]</code> gets the result of <code>2+2</code>. The last index in the first assignment is the result of <code>a[2]</code>, which has already been assigned as <code>4</code>, and its value is also given <code>a[2]</code>.</p> <p>This shows that even though any existing arrays named <code>a</code> in the current scope have already been unset by using <code>=</code> instead of <code>+=</code> to the compound assignment, arithmetic variables within keys can self-reference any elements already assigned within the same compound-assignment. With integer arrays this also applies to expressions to the right of the <code>=</code>. (See evaluation order, the right side of an arithmetic assignment is typically evaluated first in Bash.)</p> <p>The second compound assignment argument to declare uses <code>+=</code>, so it appends after the last element of the existing array rather than deleting it and creating a new array, so <code>a[5]</code> gets <code>42</code>.</p> <p>Lastly, the element whose index is the value of <code>a[4]</code> (<code>4</code>), gets <code>3</code> added to its existing value, making <code>a[4]</code> == <code>7</code>. Note that having the integer attribute set this time causes += to add, rather than append a string, as it would for a non-integer array.</p> <p>The single quotes force the assignments to be evaluated in the environment of <code>declare</code>. This is important because attributes are only applied to the assignment after assignment arguments are processed. Without them the <code>+=</code> compound assignment would have been invalid, and strings would have been inserted into the integer array without evaluating the arithmetic. A special-case of this is shown in the next section.</p> <p>info</p> <p>Bash declaration commands are really keywords in disguise. They magically parse arguments to determine whether they are in the form of a valid assignment. If so, they are evaluated as assignments. If not, they are undergo normal argument expansion before being passed to the builtin which evaluates the resulting string as an assignment (somewhat like <code>eval</code>, but there are differences.) <code>'Todo:</code>\\' Discuss this in detail.</p>"},{"location":"syntax/arrays/#indirection","title":"Indirection","text":"<p>Arrays can be expanded indirectly using the indirect parameter expansion syntax. Parameters whose values are of the form: <code>name[index]</code>, <code>name[@]</code>, or <code>name[*]</code> when expanded indirectly produce the expected results. This is mainly useful for passing arrays (especially multiple arrays) by name to a function.</p> <p>This example is an \"isSubset\"-like predicate which returns true if all key-value pairs of the array given as the first argument to isSubset correspond to a key-value of the array given as the second argument. It demonstrates both indirect array expansion and indirect key-passing without eval using the aforementioned special compound assignment expansion.</p> <pre><code>isSubset() {\n local -a 'xkeys=(\"${!'\"$1\"'[@]}\")' 'ykeys=(\"${!'\"$2\"'[@]}\")'\n set -- \"${@/%/[key]}\"\n\n (( ${#xkeys[@]} &lt;= ${#ykeys[@]} )) || return 1\n\n local key\n for key in \"${xkeys[@]}\"; do\n [[ ${!2+_} &amp;&amp; ${!1} == ${!2} ]] || return 1\n done\n}\n\nmain() {\n # \"a\" is a subset of \"b\"\n local -a 'a=({0..5})' 'b=({0..10})'\n isSubset a b\n echo $? # true\n\n # \"a\" contains a key not in \"b\"\n local -a 'a=([5]=5 {6..11})' 'b=({0..10})'\n isSubset a b\n echo $? # false\n\n # \"a\" contains an element whose value != the corresponding member of \"b\"\n local -a 'a=([5]=5 6 8 9 10)' 'b=({0..10})'\n isSubset a b\n echo $? # false\n}\n\nmain\n</code></pre> <p>This script is one way of implementing a crude multidimensional associative array by storing array definitions in an array and referencing them through indirection. The script takes two keys and dynamically calls a function whose name is resolved from the array.</p> <pre><code>callFuncs() {\n # Set up indirect references as positional parameters to minimize local name collisions.\n set -- \"${@:1:3}\" ${2+'a[\"$1\"]' \"$1\"'[\"$2\"]'}\n\n # The only way to test for set but null parameters is unfortunately to test each individually.\n local x\n for x; do\n [[ $x ]] || return 0\n done\n\n local -A a=(\n [foo]='([r]=f [s]=g [t]=h)'\n [bar]='([u]=i [v]=j [w]=k)'\n [baz]='([x]=l [y]=m [z]=n)'\n ) ${4+${a[\"$1\"]+\"${1}=${!3}\"}} # For example, if \"$1\" is \"bar\" then define a new array: bar=([u]=i [v]=j [w]=k)\n\n ${4+${a[\"$1\"]+\"${!4-:}\"}} # Now just lookup the new array. for inputs: \"bar\" \"v\", the function named \"j\" will be called, which prints \"j\" to stdout.\n}\n\nmain() {\n # Define functions named {f..n} which just print their own names.\n local fun='() { echo \"$FUNCNAME\"; }' x\n\n for x in {f..n}; do\n eval \"${x}${fun}\"\n done\n\n callFuncs \"$@\"\n}\n\nmain \"$@\"\n</code></pre>"},{"location":"syntax/arrays/#bugs-and-portability-considerations","title":"Bugs and Portability Considerations","text":"<ul> <li>Arrays are not specified by POSIX. One-dimensional indexed arrays are supported using similar syntax and semantics by most Korn-like shells.</li> <li>Associative arrays are supported via <code>typeset -A</code> in Bash 4, Zsh, and Ksh93.</li> <li>In Ksh93, arrays whose types are not given explicitly are not necessarily indexed. Arrays defined using compound assignments which specify subscripts are associative by default. In Bash, associative arrays can only be created by explicitly declaring them as associative, otherwise they are always indexed. In addition, ksh93 has several other compound structures whose types can be determined by the compound assignment syntax used to create them.</li> <li>In Ksh93, using the <code>=</code> compound assignment operator unsets the array, including any attributes that have been set on the array prior to assignment. In order to preserve attributes, you must use the <code>+=</code> operator. However, declaring an associative array, then attempting an <code>a=(...)</code> style compound assignment without specifying indexes is an error. I can't explain this inconsistency.<code>$ ksh -c 'function f { typeset -a a; a=([0]=foo [1]=bar); typeset -p a; }; f' # Attribute is lost, and since subscripts are given, we default to associative. typeset -A a=([0]=foo [1]=bar) $ ksh -c 'function f { typeset -a a; a+=([0]=foo [1]=bar); typeset -p a; }; f' # Now using += gives us the expected results. typeset -a a=(foo bar) $ ksh -c 'function f { typeset -A a; a=(foo bar); typeset -p a; }; f' # On top of that, the reverse does NOT unset the attribute. No idea why. ksh: f: line 1: cannot append index array to associative array a</code></li> <li>Only Bash and mksh support compound assignment with mixed explicit subscripts and automatically incrementing subscripts. In ksh93, in order to specify individual subscripts within a compound assignment, all subscripts must be given (or none). Zsh doesn't support specifying individual subscripts at all.</li> <li>Appending to a compound assignment is a fairly portable way to append elements after the last index of an array. In Bash, this also sets append mode for all individual assignments within the compound assignment, such that if a lower subscript is specified, subsequent elements will be appended to previous values. In ksh93, it causes subscripts to be ignored, forcing appending everything after the last element. (Appending has different meaning due to support for multi-dimensional arrays and nested compound datastructures.) <code>$ ksh -c 'function f { typeset -a a; a+=(foo bar baz); a+=([3]=blah [0]=bork [1]=blarg [2]=zooj); typeset -p a; }; f' # ksh93 forces appending to the array, disregarding subscripts typeset -a a=(foo bar baz '[3]=blah' '[0]=bork' '[1]=blarg' '[2]=zooj') $ bash -c 'function f { typeset -a a; a+=(foo bar baz); a+=(blah [0]=bork blarg zooj); typeset -p a; }; f' # Bash applies += to every individual subscript. declare -a a='([0]=\"foobork\" [1]=\"barblarg\" [2]=\"bazzooj\" [3]=\"blah\")' $ mksh -c 'function f { typeset -a a; a+=(foo bar baz); a+=(blah [0]=bork blarg zooj); typeset -p a; }; f' # Mksh does like Bash, but clobbers previous values rather than appending. set -A a typeset a[0]=bork typeset a[1]=blarg typeset a[2]=zooj typeset a[3]=blah</code></li> <li>In Bash and Zsh, the alternate value assignment parameter expansion (<code>${arr[idx]:=foo}</code>) evaluates the subscript twice, first to determine whether to expand the alternate, and second to determine the index to assign the alternate to. See evaluation order. <code>$ : ${_[$(echo $RANDOM &gt;&amp;2)1]:=$(echo hi &gt;&amp;2)} 13574 hi 14485</code></li> <li>In Zsh, arrays are indexed starting at 1 in its default mode. Emulation modes are required in order to get any kind of portability.</li> <li>Zsh and mksh do not support compound assignment arguments to <code>typeset</code>.</li> <li>Ksh88 didn't support modern compound array assignment syntax. The original (and most portable) way to assign multiple elements is to use the <code>set -A name arg1 arg2 ...</code> syntax. This is supported by almost all shells that support ksh-like arrays except for Bash. Additionally, these shells usually support an optional <code>-s</code> argument to <code>set</code> which performs lexicographic sorting on either array elements or the positional parameters. Bash has no built-in sorting ability other than the usual comparison operators. <code>$ ksh -c 'set -A arr -- foo bar bork baz; typeset -p arr' # Classic array assignment syntax typeset -a arr=(foo bar bork baz) $ ksh -c 'set -sA arr -- foo bar bork baz; typeset -p arr' # Native sorting! typeset -a arr=(bar baz bork foo) $ mksh -c 'set -sA arr -- foo \"[3]=bar\" \"[2]=baz\" \"[7]=bork\"; typeset -p arr' # Probably a bug. I think the maintainer is aware of it. set -A arr typeset arr[2]=baz typeset arr[3]=bar typeset arr[7]=bork typeset arr[8]=foo</code></li> <li>Evaluation order for assignments involving arrays varies significantly depending on context. Notably, the order of evaluating the subscript or the value first can change in almost every shell for both expansions and arithmetic variables. See evaluation order for details.</li> <li>Bash 4.1.* and below cannot use negative subscripts to address array indexes relative to the highest-numbered index. You must use the subscript expansion, i.e. <code>\"${arr[@]:(-n):1}\"</code>, to expand the nth-last element (or the next-highest indexed after <code>n</code> if <code>arr[n]</code> is unset). In Bash 4.2, you may expand (but not assign to) a negative index. In Bash 4.3, ksh93, and zsh, you may both assign and expand negative offsets.</li> <li>ksh93 also has an additional slice notation: <code>\"${arr[n..m]}\"</code> where <code>n</code> and <code>m</code> are arithmetic expressions. These are needed for use with multi-dimensional arrays.</li> <li>Assigning or referencing negative indexes in mksh causes wrap-around. The max index appears to be <code>UINT_MAX</code>, which would be addressed by <code>arr[-1]</code>.</li> <li>So far, Bash's <code>-v var</code> test doesn't support individual array subscripts. You may supply an array name to test whether an array is defined, but can't check an element. ksh93's <code>-v</code> supports both. Other shells lack a <code>-v</code> test.</li> </ul>"},{"location":"syntax/arrays/#bugs","title":"Bugs","text":"<ul> <li>Fixed in 4.3 Bash 4.2.* and earlier considers each chunk of a compound assignment, including the subscript for globbing. The subscript part is considered quoted, but any unquoted glob characters on the right-hand side of the <code>[...]=</code> will be clumped with the subscript and counted as a glob. Therefore, you must quote anything on the right of the <code>=</code> sign. This is fixed in 4.3, so that each subscript assignment statement is expanded following the same rules as an ordinary assignment. This also works correctly in ksh93. <code>$ touch '[1]=a'; bash -c 'a=([1]=*); echo \"${a[@]}\"' [1]=a</code> mksh has a similar but even worse problem in that the entire subscript is considered a glob. <code>$ touch 1=a; mksh -c 'a=([123]=*); print -r -- \"${a[@]}\"' 1=a</code></li> <li> <p>Fixed in 4.3 In addition to the above globbing issue, assignments preceding \"declare\" have an additional effect on brace and pathname expansion. `$ set -x; foo=bar declare arr=( {1..10} )</p> <ul> <li>foo=bar</li> <li>declare 'arr=(1)' 'arr=(2)' 'arr=(3)' 'arr=(4)' 'arr=(5)' 'arr=(6)' 'arr=(7)' 'arr=(8)' 'arr=(9)' 'arr=(10)'</li> </ul> <p>$ touch xy=foo + touch xy=foo $ declare x[y]= + declare 'x[y]=' $ foo=bar declare x[y]=* + foo=bar + declare xy=foo <code>Each word (the entire assignment) is subject to globbing and brace expansion. This appears to trigger the same strange expansion mode as</code>let<code>,</code>eval<code>, other declaration commands, and maybe more. - **Fixed in 4.3** Indirection combined with another modifier expands arrays to a single word.</code>$ a=({a..c}) b=a[@]; printf '&lt;%s&gt; ' \"${!b}\"; echo; printf '&lt;%s&gt; ' \"${!b/%/foo}\"; echo <code>- **Fixed in 4.3** Process substitutions are evaluated within array indexes. Zsh and ksh don't do this in any arithmetic context.</code># print \"moo\" dev=fd=1 _[1&lt;(echo moo &gt;&amp;2)]="},{"location":"syntax/arrays/#fork-bomb","title":"Fork bomb","text":"<p>${dev[${dev='dev[1&gt;(${dev[dev]})]'}]} `</p>"},{"location":"syntax/arrays/#evaluation-order","title":"Evaluation order","text":"<p>Here are some of the nasty details of array assignment evaluation order. You can use this testcase code to generate these results.</p> <pre><code>Each testcase prints evaluation order for indexed array assignment\ncontexts. Each context is tested for expansions (represented by digits) and\narithmetic (letters), ordered from left to right within the expression. The\noutput corresponds to the way evaluation is re-ordered for each shell:\n\na[ $1 a ]=${b[ $2 b ]:=${c[ $3 c ]}} No attributes\na[ $1 a ]=${b[ $2 b ]:=c[ $3 c ]} typeset -ia a\na[ $1 a ]=${b[ $2 b ]:=c[ $3 c ]} typeset -ia b\na[ $1 a ]=${b[ $2 b ]:=c[ $3 c ]} typeset -ia a b\n(( a[ $1 a ] = b[ $2 b ] ${c[ $3 c ]} )) No attributes\n(( a[ $1 a ] = ${b[ $2 b ]:=c[ $3 c ]} )) typeset -ia b\na+=( [ $1 a ]=${b[ $2 b ]:=${c[ $3 c ]}} [ $4 d ]=$(( $5 e )) ) typeset -a a\na+=( [ $1 a ]=${b[ $2 b ]:=c[ $3 c ]} [ $4 d ]=${5}e ) typeset -ia a\n\nbash: 4.2.42(1)-release\n2 b 3 c 2 b 1 a\n2 b 3 2 b 1 a c\n2 b 3 2 b c 1 a\n2 b 3 2 b c 1 a c\n1 2 3 c b a\n1 2 b 3 2 b c c a\n1 2 b 3 c 2 b 4 5 e a d\n1 2 b 3 2 b 4 5 a c d e\n\nksh93: Version AJM 93v- 2013-02-22\n1 2 b b a\n1 2 b b a\n1 2 b b a\n1 2 b b a\n1 2 3 c b a\n1 2 b b a\n1 2 b b a 4 5 e d\n1 2 b b a 4 5 d e\n\nmksh: @(#)MIRBSD KSH R44 2013/02/24\n2 b 3 c 1 a\n2 b 3 1 a c\n2 b 3 c 1 a\n2 b 3 c 1 a\n1 2 3 c a b\n1 2 b 3 c a\n1 2 b 3 c 4 5 e a d\n1 2 b 3 4 5 a c d e\n\nzsh: 5.0.2\n2 b 3 c 2 b 1 a\n2 b 3 2 b 1 a c\n2 b 1 a\n2 b 1 a\n1 2 3 c b a\n1 2 b a\n1 2 b 3 c 2 b 4 5 e\n1 2 b 3 2 b 4 5\n</code></pre>"},{"location":"syntax/arrays/#see-also","title":"See also","text":"<ul> <li>Parameter expansion (contains sections for arrays)</li> <li>classic_for (contains some examples to iterate over arrays)</li> <li>declare</li> <li>BashFAQ 005 - How can I use array variables? - A very detailed discussion on arrays with many examples.</li> <li>BashSheet - Arrays - Bashsheet quick-reference on Greycat's wiki.</li> </ul>"},{"location":"syntax/basicgrammar/","title":"Basic grammar rules of Bash","text":"<p>Bash builds its features on top of a few basic grammar rules. The code you see everywhere, the code you use, is based on those rules. However, this is a very theoretical view, but if you're interested, it may help you understand why things look the way they look.</p> <p>If you don't know the commands used in the following examples, just trust the explanation.</p>","tags":["bash","shell","scripting","grammar","syntax","language"]},{"location":"syntax/basicgrammar/#simple-commands","title":"Simple Commands","text":"<p>Bash manual says:</p> <pre><code>A simple command is a sequence of optional variable assignments followed by blank-separated words and redirections,\nand terminated by a control operator. The first word specifies the command to be executed, and is passed as argument\nzero. The remaining words are passed as arguments to the invoked command.\n</code></pre> <p>Sounds harder than it actually is. It is what you do daily. You enter simple commands with parameters, and the shell executes them.</p> <p>Every complex Bash operation can be split into simple commands:</p> <pre><code>ls\nls &gt; list.txt\nls -l\nLC_ALL=C ls\n</code></pre> <p>The last one might not be familiar. That one simply adds \"<code>LC_ALL=C</code>\" to the environment of the <code>ls</code> program. It doesn't affect your current shell. This also works while calling functions, unless Bash runs in POSIX\u00ae mode (in which case it affects your current shell).</p> <p>Every command has an exit code. It's a type of return status. The shell can catch it and act on it. Exit code range is from 0 to 255, where 0 means success, and the rest mean either something failed, or there is an issue to report back to the calling program.</p> <p>info</p> <p>The simple command construct is the base for all higher constructs. Everything you execute, from pipelines to functions, finally ends up in (many) simple commands. That's why Bash only has one method to expand and execute a simple command.</p>","tags":["bash","shell","scripting","grammar","syntax","language"]},{"location":"syntax/basicgrammar/#pipelines","title":"Pipelines","text":"<p>FIXME</p> <p>Missing an additional article about pipelines and pipelining</p> <p><code>[time [-p]] [ ! ] command [ | command2 ... ]</code></p> <p>Don't get confused about the name \"pipeline.\" It's a grammatic name for a construct. Such a pipeline isn't necessarily a pair of commands where stdout/stdin is connected via a real pipe.</p> <p>Pipelines are one or more simple commands (separated by the <code>|</code> symbol connects their input and output), for example:</p> <pre><code>ls /etc | wc -l\n</code></pre> <p>will execute <code>ls</code> on <code>/etc</code> and pipe the output to <code>wc</code>, which will count the lines generated by the ls command. The result is the number of directory entries in /etc.</p> <p>The last command in the pipeline will set the exit code for the pipeline. This exit code can be \"inverted\" by prefixing an exclamation mark to the pipeline: An unsuccessful pipeline will exit \"successful\" and vice versa. In this example, the commands in the if stanza will be executed if the pattern \"^root:\" is not found in <code>/etc/passwd</code>:</p> <pre><code>if ! grep '^root:' /etc/passwd; then\n echo \"No root user defined... eh?\"\nfi\n</code></pre> <p>Yes, this is also a pipeline (although there is no pipe!), because the exclamation mark to invert the exit code can only be used in a pipeline. If <code>grep</code>'s exit code is 1 (FALSE) (the text was not found), the leading <code>!</code> will \"invert\" the exit code, and the shell sees (and acts on) exit code 0 (TRUE) and the <code>then</code> part of the <code>if</code> stanza is executed. One could say we checked for \"<code>not grep \"^root\" /etc/passwd</code>\".</p> <p>The set option pipefail determines the behavior of how bash reports the exit code of a pipeline. If it's set, then the exit code (<code>$?</code>) is the last command that exits with non zero status, if none fail, it's zero. If it's not set, then <code>$?</code> always holds the exit code of the last command (as explained above).</p> <p>The shell option <code>lastpipe</code> will execute the last element in a pipeline construct in the current shell environment, i.e. not a subshell.</p> <p>There's also an array <code>PIPESTATUS[]</code> that is set after a foreground pipeline is executed. Each element of <code>PIPESTATUS[]</code> reports the exit code of the respective command in the pipeline. Note: (1) it's only for foreground pipe and (2) for higher level structure that is built up from a pipeline. Like list, <code>PIPESTATUS[]</code> holds the exit status of the last pipeline command executed.</p> <p>Another thing you can do with pipelines is log their execution time. Note that <code>time</code> is not a command, it is part of the pipeline syntax:</p> <pre><code># time updatedb\nreal 3m21.288s\nuser 0m3.114s\nsys 0m4.744s\n</code></pre>","tags":["bash","shell","scripting","grammar","syntax","language"]},{"location":"syntax/basicgrammar/#lists","title":"Lists","text":"<p>FIXME</p> <p>Missing an additional article about list operators</p> <p>A list is a sequence of one or more pipelines separated by one of the operators <code>;</code>, <code>&amp;</code>, <code>&amp;&amp;</code>, or <code>\u2502\u2502</code>, and optionally terminated by one of <code>;</code>, <code>&amp;</code>, or <code>&lt;newline&gt;</code>.</p> <p>=&gt; It's a group of pipelines separated or terminated by tokens that all have different meanings for Bash.</p> <p>Your whole Bash script technically is one big single list!</p> Operator Description <code>&lt;PIPELINE1&gt; &lt;newline&gt; &lt;PIPELINE2&gt;</code> Newlines completely separate pipelines. The next pipeline is executed without any checks. (You enter a command and press <code>&lt;RETURN&gt;</code>!) <code>&lt;PIPELINE1&gt; ; &lt;PIPELINE2&gt;</code> The semicolon does what <code>&lt;newline&gt;</code> does: It separates the pipelines <code>&lt;PIPELINE&gt; &amp; &lt;PIPELINE&gt;</code> The pipeline in front of the <code>&amp;</code> is executed asynchronously (\"in the background\"). If a pipeline follows this, it is executed immediately after the async pipeline starts <code>&lt;PIPELINE1&gt; &amp;&amp; &lt;PIPELINE2&gt;</code> <code>&lt;PIPELINE1&gt;</code> is executed and only if its exit code was 0 (TRUE), then <code>&lt;PIPELINE2&gt;</code> is executed (AND-List) <code>&lt;PIPELINE1&gt;||&lt;PIPELINE2&gt;</code> <code>&lt;PIPELINE1&gt;</code> is executed and only if its exit code was not 0 (FALSE), then <code>&lt;PIPELINE2&gt;</code> is executed (OR-List) <p>Note: POSIX calls this construct a \"compound lists\".</p>","tags":["bash","shell","scripting","grammar","syntax","language"]},{"location":"syntax/basicgrammar/#compound-commands","title":"Compound Commands","text":"<p>See also the list of compound commands.</p> <p>There are two forms of compound commands:</p> <ul> <li>form a new syntax element using a list as a \"body\"</li> <li>completly independant syntax elements</li> </ul> <p>Essentially, everything else that's not described in this article. Compound commands have the following characteristics:</p> <ul> <li>they begin and end with a specific keyword or operator (e.g. <code>for ... done</code>)</li> <li>they can be redirected as a whole</li> </ul> <p>See the following table for a short overview (no details - just an overview):</p> Compound command syntax Description <code>( &lt;LIST&gt; )</code> Execute <code>&lt;LIST&gt;</code> in an extra subshell =&gt; article <code>{ &lt;LIST&gt; ; }</code> Execute <code>&lt;LIST&gt;</code> as separate group (but not in a subshell) =&gt; article <code>(( &lt;EXPRESSION&gt; ))</code> Evaluate the arithmetic expression <code>&lt;EXPRESSION&gt;</code> =&gt; article <code>[[ &lt;EXPRESSION&gt; ]]</code> Evaluate the conditional expression <code>&lt;EXPRESSION&gt;</code> (aka \"the new test command\") =&gt; article <code>for &lt;NAME&gt; in &lt;WORDS&gt; ; do &lt;LIST&gt; ; done</code> Executes <code>&lt;LIST&gt;</code> while setting the variable <code>&lt;NAME&gt;</code> to one of <code>&lt;WORDS&gt;</code> on every iteration (classic for-loop) =&gt; article <code>for (( &lt;EXPR1&gt; ; &lt;EXPR2&gt; ; &lt;EXPR3&gt; )) ; do &lt;LIST&gt; ; done</code> C-style for-loop (driven by arithmetic expressions) =&gt; article <code>select &lt;NAME&gt; in &lt;WORDS&gt; ; do &lt;LIST&gt; ; done</code> Provides simple menus =&gt; article <code>case &lt;WORD&gt; in &lt;PATTERN&gt;) &lt;LIST&gt; ;; ... esac</code> Decisions based on pattern matching - executing <code>&lt;LIST&gt;</code> on match =&gt; article <code>if &lt;LIST&gt; ; then &lt;LIST&gt; ; else &lt;LIST&gt; ; fi</code> The if clause: makes decisions based on exit codes =&gt; article <code>while &lt;LIST1&gt; ; do &lt;LIST2&gt; ; done</code> Execute <code>&lt;LIST2&gt;</code> while <code>&lt;LIST1&gt;</code> returns TRUE (exit code) =&gt; article <code>until &lt;LIST1&gt; ; do &lt;LIST2&gt; ; done</code> Execute <code>&lt;LIST2&gt;</code> until <code>&lt;LIST1&gt;</code> returns TRUE (exit code) =&gt; article","tags":["bash","shell","scripting","grammar","syntax","language"]},{"location":"syntax/basicgrammar/#shell-function-definitions","title":"Shell Function Definitions","text":"<p>FIXME</p> <p>Missing an additional article about shell functions</p> <p>A shell function definition makes a compound command available via a new name. When the function runs, it has its own \"private\" set of positional parameters and I/O descriptors. It acts like a script-within-the-script. Simply stated: You've created a new command.</p> <p>The definition is easy (one of many possibilities):</p> <p><code>&lt;NAME&gt; () &lt;COMPOUND_COMMAND&gt; &lt;REDIRECTIONS&gt;</code></p> <p>which is usually used with the <code>{...; }</code> compound command, and thus looks like:</p> <pre><code>print_help() { echo \"Sorry, no help available\"; }\n</code></pre> <p>As above, a function definition can have any compound command as a body. Structures like</p> <pre><code>countme() for ((x=1;x&lt;=9;x++)); do echo $x; done\n</code></pre> <p>are unusual, but perfectly valid, since the for loop construct is a compound command!</p> <p>If redirection is specified, the redirection is not performed when the function is defined. It is performed when the function runs:</p> <pre><code># this will NOT perform the redirection (at definition time)\nf() { echo ok ; } &gt; file\n\n# NOW the redirection will be performed (during EXECUTION of the function)\nf\n</code></pre> <p>Bash allows three equivalent forms of the function definition:</p> <pre><code>NAME () &lt;COMPOUND_COMMAND&gt; &lt;REDIRECTIONS&gt;\nfunction NAME () &lt;COMPOUND_COMMAND&gt; &lt;REDIRECTIONS&gt;\nfunction NAME &lt;COMPOUND_COMMAND&gt; &lt;REDIRECTIONS&gt;\n</code></pre> <p>The space between <code>NAME</code> and <code>()</code> is optional, usually you see it without the space.</p> <p>I suggest using the first form. It's specified in POSIX and all Bourne-like shells seem to support it.</p> <p>Note: Before version <code>2.05-alpha1</code>, Bash only recognized the definition using curly braces (<code>name() { ... }</code>), other shells allow the definition using any command (not just the compound command set).</p> <p>To execute a function like a regular shell script you put it together like this:</p> <pre><code>#!/bin/bash\n# Add shebang\n\nmycmd()\n{\n # this $1 belongs to the function!\n find / -iname \"$1\"\n}\n\n# this $1 belongs the script itself!\nmycmd \"$1\" # Execute command immediately after defining function\n\nexit 0\n</code></pre> <p>Just informational(1):</p> <p>Internally, for forking, Bash stores function definitions in environment variables. Variables with the content \"() ....\".</p> <p>Something similar to the following works without \"officially\" declaring a function:</p> <pre><code>$ export testfn=\"() { echo test; }\"\n$ bash -c testfn\ntest\n$\n</code></pre> <p>Just informational(2):</p> <p>It is possible to create function names containing slashes:</p> <pre><code>/bin/ls() {\n echo LS FAKE\n}\n</code></pre> <p>The elements of this name aren't subject to a path search.</p> <p>Weird function names should not be used. Quote from the maintainer:</p> <ul> <li> <ul> <li>It was a mistake to allow such characters in function names (<code>unset</code> doesn't work to unset them without forcing <code>-f</code>, for instance). We're stuck with them for backwards compatibility, but I don't have to encourage their use. *</li> </ul> </li> </ul>","tags":["bash","shell","scripting","grammar","syntax","language"]},{"location":"syntax/basicgrammar/#grammar-summary","title":"Grammar summary","text":"<ul> <li>a simple command is just a command and its arguments</li> <li>a pipeline is one or more simple command probably connected in a pipe</li> <li>a list is one or more pipelines connected by special operators</li> <li>a compound command is a list or a special command that forms a new meta-command</li> <li>a function definition makes a compound command available under a new name, and a separate environment</li> </ul>","tags":["bash","shell","scripting","grammar","syntax","language"]},{"location":"syntax/basicgrammar/#examples-for-classification","title":"Examples for classification","text":"<p>FIXME</p> <p>more...</p> <p>A (very) simple command</p> <pre><code>echo \"Hello world...\"\n</code></pre> <p>All of the following are simple commands</p> <pre><code>x=5\n\n&gt;tmpfile\n\n{x}&lt;\"$x\" _=${x=&lt;(echo moo)} &lt;&amp;0$(cat &lt;&amp;\"$x\" &gt;&amp;2)\n</code></pre> <p>A common compound command</p> <pre><code>if [ -d /data/mp3 ]; then\n cp mymusic.mp3 /data/mp3\nfi\n</code></pre> <ul> <li>the compound command for the <code>if</code> clause</li> <li>the list that <code>if</code> checks actually contains the simple command <code>[ -d /data/mp3 ]</code></li> <li>the list that <code>if</code> executes contains a simple command (<code>cp mymusic.mp3 /data/mp3</code>)</li> </ul> <p>Let's invert test command exit code, only one thing changes:</p> <pre><code>if ! [ -d /data/mp3 ]; then\n cp mymusic.mp3 /data/mp3\nfi\n</code></pre> <ul> <li>the list that <code>if</code> checks contains a pipeline now (because of the <code>!</code>)</li> </ul>","tags":["bash","shell","scripting","grammar","syntax","language"]},{"location":"syntax/basicgrammar/#see-also","title":"See also","text":"<ul> <li>Internal: List of compound commands</li> <li>Internal: Parsing and execution of simple commands</li> <li>Internal: Quoting and escaping</li> <li>Internal: Introduction to expansions and substitutions</li> <li>Internal: Some words about words...</li> </ul>","tags":["bash","shell","scripting","grammar","syntax","language"]},{"location":"syntax/pattern/","title":"Patterns and pattern matching","text":"<p>A pattern is a string description. Bash uses them in various ways:</p> <ul> <li>Pathname expansion (Globbing - matching filenames)</li> <li>Pattern matching in conditional expressions</li> <li>Substring removal and search and replace in Parameter Expansion</li> <li>Pattern-based branching using the case command</li> </ul> <p>The pattern description language is relatively easy. Any character that's not mentioned below matches itself. The <code>NUL</code> character may not occur in a pattern. If special characters are quoted, they're matched literally, i.e., without their special meaning.</p> <p>Do not confuse patterns with regular expressions, because they share some symbols and do similar matching work.</p>","tags":["bash","shell","scripting","glob","globbing","wildcards","filename","pattern","matching"]},{"location":"syntax/pattern/#normal-pattern-language","title":"Normal pattern language","text":"Sequence Description <code>*</code> Matches any string, including the null string (empty string) <code>?</code> Matches any single character <code>X</code> Matches the character <code>X</code> which can be any character that has no special meaning <code>\\X</code> Matches the character <code>X</code>, where the character's special meaning is stripped by the backslash <code>\\\\</code> Matches a backslash <code>[...]</code> Defines a pattern bracket expression (see below). Matches any of the enclosed characters at this position.","tags":["bash","shell","scripting","glob","globbing","wildcards","filename","pattern","matching"]},{"location":"syntax/pattern/#bracket-expressions","title":"Bracket expressions","text":"<p>The bracket expression <code>[...]</code> mentioned above has some useful applications:</p> Bracket expression Description <code>[XYZ]</code> The \"normal\" bracket expression, matching either <code>X</code>, <code>Y</code> or <code>Z</code> <code>[X-Z]</code> A range expression: Matching all the characters from <code>X</code> to <code>Y</code> (your current locale, defines how the characters are sorted!) <code>[[:class:]]</code> Matches all the characters defined by a POSIX\u00ae character class: <code>alnum</code>, <code>alpha</code>, <code>ascii</code>, <code>blank</code>, <code>cntrl</code>, <code>digit</code>, <code>graph</code>, <code>lower</code>, <code>print</code>, <code>punct</code>, <code>space</code>, <code>upper</code>, <code>word</code> and <code>xdigit</code> <code>[^...]</code> A negating expression: It matches all the characters that are not in the bracket expression <code>[!...]</code> Equivalent to <code>[^...]</code> <code>[]...]</code> or <code>[-...]</code> Used to include the characters <code>]</code> and <code>-</code> into the set, they need to be the first characters after the opening bracket <code>[=C=]</code> Matches any character that is eqivalent to the collation weight of <code>C</code> (current locale!) <code>[[.SYMBOL.]]</code> Matches the collating symbol <code>SYMBOL</code>","tags":["bash","shell","scripting","glob","globbing","wildcards","filename","pattern","matching"]},{"location":"syntax/pattern/#examples","title":"Examples","text":"<p>Some simple examples using normal pattern matching:</p> <ul> <li>Pattern <code>\"Hello world\"</code> matches<ul> <li><code>Hello world</code></li> </ul> </li> <li>Pattern <code>[Hh]\"ello world\"</code> matches<ul> <li>=&gt; <code>Hello world</code></li> <li>=&gt; <code>hello world</code></li> </ul> </li> <li>Pattern <code>Hello*</code> matches (for example)<ul> <li>=&gt; <code>Hello world</code></li> <li>=&gt; <code>Helloworld</code></li> <li>=&gt; <code>HelloWoRlD</code></li> <li>=&gt; <code>Hello</code></li> </ul> </li> <li>Pattern <code>Hello world[[:punct:]]</code> matches (for example)<ul> <li>=&gt; <code>Hello world!</code></li> <li>=&gt; <code>Hello world.</code></li> <li>=&gt; <code>Hello world+</code></li> <li>=&gt; <code>Hello world?</code></li> </ul> </li> <li>Pattern <code>[[.backslash.]]Hello[[.vertical-line.]]world[[.exclamation-mark.]]</code> matches (using collation symbols)<ul> <li>=&gt; <code>\\Hello|world!</code></li> </ul> </li> </ul>","tags":["bash","shell","scripting","glob","globbing","wildcards","filename","pattern","matching"]},{"location":"syntax/pattern/#extended-pattern-language","title":"Extended pattern language","text":"<p>If you set the shell option <code>extglob</code>, Bash understands some powerful patterns. A <code>&lt;PATTERN-LIST&gt;</code> is one or more patterns, separated by the pipe-symbol (<code>PATTERN|PATTERN</code>).</p> Extended pattern Matches <code>?(&lt;PATTERN-LIST&gt;)</code> Matches zero or one occurrence of the given patterns <code>*(&lt;PATTERN-LIST&gt;)</code> Matches zero or more occurrences of the given patterns <code>+(&lt;PATTERN-LIST&gt;)</code> Matches one or more occurrences of the given patterns <code>@(&lt;PATTERN-LIST&gt;)</code> Matches one of the given patterns <code>!(&lt;PATTERN-LIST&gt;)</code> Matches anything except one of the given patterns","tags":["bash","shell","scripting","glob","globbing","wildcards","filename","pattern","matching"]},{"location":"syntax/pattern/#examples_1","title":"Examples","text":"<p>Delete all but one specific file</p> <pre><code>rm -f !(survivior.txt)\n</code></pre>","tags":["bash","shell","scripting","glob","globbing","wildcards","filename","pattern","matching"]},{"location":"syntax/pattern/#pattern-matching-configuration","title":"Pattern matching configuration","text":"","tags":["bash","shell","scripting","glob","globbing","wildcards","filename","pattern","matching"]},{"location":"syntax/pattern/#related-shell-options","title":"Related shell options","text":"option classification description <code>dotglob</code> globbing see Pathname expansion customization <code>extglob</code> global enable/disable extended pattern matching language, as described above <code>failglob</code> globbing see Pathname expansion customization <code>nocaseglob</code> globbing see Pathname expansion customization <code>nocasematch</code> pattern/string matching perform pattern matching without regarding the case of individual letters <code>nullglob</code> globbing see Pathname expansion customization <code>globasciiranges</code> globbing see Pathname expansion customization","tags":["bash","shell","scripting","glob","globbing","wildcards","filename","pattern","matching"]},{"location":"syntax/pattern/#bugs-and-portability-considerations","title":"Bugs and Portability considerations","text":"<p>* Counter-intuitively, only the <code>[!chars]</code> syntax for negating a character class is specified by POSIX for shell pattern matching. <code>[^chars]</code> is merely a commonly-supported extension. Even dash supports <code>[^chars]</code>, but not posh.</p> <p>* All of the extglob quantifiers supported by bash were supported by ksh88. The set of extglob quantifiers supported by ksh88 are identical to those supported by Bash, mksh, ksh93, and zsh.</p> <p>* mksh does not support POSIX character classes. Therefore, character ranges like <code>[0-9]</code> are somewhat more portable than an equivalent POSIX class like <code>[:digit:]</code>.</p> <p>* Bash uses a custom runtime interpreter for pattern matching. (at least) ksh93 and zsh translate patterns into regexes and then use a regex compiler to emit and cache optimized pattern matching code. This means Bash may be an order of magnitude or more slower in cases that involve complex back-tracking (usually that means extglob quantifier nesting). You may wish to use Bash's regex support (the <code>=~</code> operator) if performance is a problem, because Bash will use your C library regex implementation rather than its own pattern matcher.</p> <p>TODO: describe the pattern escape bug https://gist.github.com/ormaaj/6195070</p>","tags":["bash","shell","scripting","glob","globbing","wildcards","filename","pattern","matching"]},{"location":"syntax/pattern/#ksh93-extras","title":"ksh93 extras","text":"<p>ksh93 supports some very powerful pattern matching features in addition to those described above.</p> <p>* ksh93 supports arbitrary quantifiers just like ERE using the <code>{from,to}(pattern-list)</code> syntax. <code>{2,4}(foo)bar</code> matches between 2-4 \"foo\"'s followed by \"bar\". <code>{2,}(foo)bar</code> matches 2 or more \"foo\"'s followed by \"bar\". You can probably figure out the rest. So far, none of the other shells support this syntax.</p> <p>* In ksh93, a <code>pattern-list</code> may be delimited by either <code>&amp;</code> or <code>|</code>. <code>&amp;</code> means \"all patterns must be matched\" instead of \"any pattern\". For example, <code>[[ fo0bar == @(fo[0-9]&amp;+([[:alnum:]]))bar ]]</code> would be true while <code>[[ f00bar == @(fo[0-9]&amp;+([[:alnum:]]))bar ]]</code> is false, because all members of the and-list must be satisfied. No other shell supports this so far, but you can simulate some cases in other shells using double extglob negation. The aforementioned ksh93 pattern is equivalent in Bash to: <code>[[ fo0bar == !(!(fo[0-9])|!(+([[:alnum:]])))bar ]]</code>, which is technically more portable, but ugly.</p> <p>* ksh93's printf builtin can translate from shell patterns to ERE and back again using the <code>%R</code> and <code>%P</code> format specifiers respectively.</p> <p>TODO: <code>~()</code> (and regex), <code>.sh.match</code>, backrefs, special <code>${var/.../...}</code> behavior, <code>%()</code></p>","tags":["bash","shell","scripting","glob","globbing","wildcards","filename","pattern","matching"]},{"location":"syntax/pe/","title":"Parameter expansion","text":"","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#introduction","title":"Introduction","text":"<p>One core functionality of Bash is to manage parameters. A parameter is an entity that stores values and is referenced by a name, a number or a special symbol.</p> <ul> <li>parameters referenced by a name are called variables (this also applies to arrays)</li> <li>parameters referenced by a number are called positional parameters and reflect the arguments given to a shell</li> <li>parameters referenced by a special symbol are auto-set parameters that have different special meanings and uses</li> </ul> <p>Parameter expansion is the procedure to get the value from the referenced entity, like expanding a variable to print its value. On expansion time you can do very nasty things with the parameter or its value. These things are described here.</p> <p>If you saw some parameter expansion syntax somewhere, and need to check what it can be, try the overview section below!</p> <p>Arrays can be special cases for parameter expansion, every applicable description mentions arrays below. Please also see the article about arrays.</p> <p>For a more technical view what a parameter is and which types exist, see the dictionary entry for \"parameter\".</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#overview","title":"Overview","text":"<p>Looking for a specific syntax you saw, without knowing the name?</p> <ul> <li>Simple usage<ul> <li><code>$PARAMETER</code></li> <li><code>${PARAMETER}</code></li> </ul> </li> <li>Indirection<ul> <li><code>${!PARAMETER}</code></li> </ul> </li> <li>Case modification<ul> <li><code>${PARAMETER^}</code></li> <li><code>${PARAMETER^^}</code></li> <li><code>${PARAMETER,}</code></li> <li><code>${PARAMETER,,}</code></li> <li><code>${PARAMETER~}</code></li> <li><code>${PARAMETER~~}</code></li> </ul> </li> <li>Variable name expansion<ul> <li><code>${!PREFIX*}</code></li> <li><code>${!PREFIX@}</code></li> </ul> </li> <li>Substring removal (also for filename manipulation!)<ul> <li><code>${PARAMETER#PATTERN}</code></li> <li><code>${PARAMETER##PATTERN}</code></li> <li><code>${PARAMETER%PATTERN}</code></li> <li><code>${PARAMETER%%PATTERN}</code></li> </ul> </li> <li>Search and replace<ul> <li><code>${PARAMETER/PATTERN/STRING}</code></li> <li><code>${PARAMETER//PATTERN/STRING}</code></li> <li><code>${PARAMETER/PATTERN}</code></li> <li><code>${PARAMETER//PATTERN}</code></li> </ul> </li> <li>String length<ul> <li><code>${#PARAMETER}</code></li> </ul> </li> <li>Substring expansion<ul> <li><code>${PARAMETER:OFFSET}</code></li> <li><code>${PARAMETER:OFFSET:LENGTH}</code></li> </ul> </li> <li>Use a default value<ul> <li><code>${PARAMETER:-WORD}</code></li> <li><code>${PARAMETER-WORD}</code></li> </ul> </li> <li>Assign a default value<ul> <li><code>${PARAMETER:=WORD}</code></li> <li><code>${PARAMETER=WORD}</code></li> </ul> </li> <li>Use an alternate value<ul> <li><code>${PARAMETER:+WORD}</code></li> <li><code>${PARAMETER+WORD}</code></li> </ul> </li> <li>Display error if null or unset<ul> <li><code>${PARAMETER:?WORD}</code></li> <li><code>${PARAMETER?WORD}</code></li> </ul> </li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#simple-usage","title":"Simple usage","text":"<p><code>$PARAMETER</code></p> <p><code>${PARAMETER}</code></p> <p>The easiest form is to just use a parameter's name within braces. This is identical to using <code>$FOO</code> like you see it everywhere, but has the advantage that it can be immediately followed by characters that would be interpreted as part of the parameter name otherwise. Compare these two expressions (<code>WORD=\"car\"</code> for example), where we want to print a word with a trailing \"s\":</p> <pre><code>echo \"The plural of $WORD is most likely $WORDs\"\necho \"The plural of $WORD is most likely ${WORD}s\"\n</code></pre> <p>Why does the first one fail? It prints nothing, because a parameter (variable) named \"<code>WORDs</code>\" is undefined and thus printed as \"\" (nothing). Without using braces for parameter expansion, Bash will interpret the sequence of all valid characters from the introducing \"<code>$</code>\" up to the last valid character as name of the parameter. When using braces you just force Bash to only interpret the name inside your braces.</p> <p>Also, please remember, that parameter names are (like nearly everything in UNIX\u00ae) case sensitive!</p> <p>The second form with the curly braces is also needed to access positional parameters (arguments to a script) beyond <code>$9</code>:</p> <pre><code>echo \"Argument 1 is: $1\"\necho \"Argument 10 is: ${10}\"\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#simple-usage-arrays","title":"Simple usage: Arrays","text":"<p>See also the article about general array syntax</p> <p>For arrays you always need the braces. The arrays are expanded by individual indexes or mass arguments. An individual index behaves like a normal parameter, for the mass expansion, please read the article about arrays linked above.</p> <ul> <li><code>${array[5]}</code></li> <li><code>${array[*]}</code></li> <li><code>${array[@]}</code></li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#indirection","title":"Indirection","text":"<p><code>${!PARAMETER}</code></p> <p>In some cases, like for example</p> <pre><code>${PARAMETER}\n\n${PARAMETER:0:3}\n</code></pre> <p>you can instead use the form</p> <pre><code>${!PARAMETER}\n</code></pre> <p>to enter a level of indirection. The referenced parameter is not <code>PARAMETER</code> itself, but the parameter whose name is stored as the value of <code>PARAMETER</code>. If the parameter <code>PARAMETER</code> has the value \"<code>TEMP</code>\", then <code>${!PARAMETER}</code> will expand to the value of the parameter named <code>TEMP</code>:</p> <pre><code>read -rep 'Which variable do you want to inspect? ' look_var\n\nprintf 'The value of \"%s\" is: \"%s\"\\n' \"$look_var\" \"${!look_var}\"\n</code></pre> <p>Of course the indirection also works with special variables:</p> <pre><code># set some fake positional parameters\nset one two three four\n\n# get the LAST argument (\"#\" stores the number of arguments, so \"!#\" will reference the LAST argument)\necho ${!#}\n</code></pre> <p>You can think of this mechanism as being roughly equivalent to taking any parameter expansion that begins with the parameter name, and substituting the <code>!PARAMETER</code> part with the value of PARAMETER.</p> <pre><code>echo \"${!var^^}\"\n# ...is equivalent to\neval 'echo \"${'\"$var\"'^^}\"'\n</code></pre> <p>It was an unfortunate design decision to use the <code>!</code> prefix for indirection, as it introduces parsing ambiguity with other parameter expansions that begin with <code>!</code>. Indirection is not possible in combination with any parameter expansion whose modifier requires a prefix to the parameter name. Specifically, indirection isn't possible on the <code>${!var@}</code>, <code>${!var*}</code>, <code>${!var[@]}</code>, <code>${!var[*]}</code>, and <code>${#var}</code> forms. This means the <code>!</code> prefix can't be used to retrieve the indices of an array, the length of a string, or number of elements in an array indirectly (see syntax/arrays#indirection for workarounds). Additionally, the <code>!</code>-prefixed parameter expansion conflicts with ksh-like shells which have the more powerful \"name-reference\" form of indirection, where the exact same syntax is used to expand to the name of the variable being referenced.</p> <p>Indirect references to array names are also possible since the Bash 3 series (exact version unknown), but undocumented. See syntax/arrays#indirection for details.</p> <p>Chet has added an initial implementation of the ksh <code>nameref</code> declaration command to the git devel branch. (<code>declare -n</code>, <code>local -n</code>, etc, will be supported). This will finally address many issues around passing and returning complex datatypes to/from functions.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#case-modification","title":"Case modification","text":"<p><code>${PARAMETER^}</code></p> <p><code>${PARAMETER^^}</code></p> <p><code>${PARAMETER,}</code></p> <p><code>${PARAMETER,,}</code></p> <p><code>${PARAMETER~}</code></p> <p><code>${PARAMETER~~}</code></p> <p>These expansion operators modify the case of the letters in the expanded text.</p> <p>The <code>^</code> operator modifies the first character to uppercase, the <code>,</code> operator to lowercase. When using the double-form (<code>^^</code> and <code>,,</code>), all characters are converted.</p> <p>Info</p> <p>The (currently undocumented) operators <code>~</code> and <code>~~</code> reverse the case of the given text (in <code>PARAMETER</code>).<code>~</code> reverses the case of first letter of words in the variable while <code>~~</code> reverses case for all. Thanks to <code>Bushmills</code> and <code>geirha</code> on the Freenode IRC channel for this finding.</p> <p>Example: Rename all <code>*.txt</code> filenames to lowercase</p> <pre><code>for file in *.txt; do\n mv \"$file\" \"${file,,}\"\ndone\n</code></pre> <p>Note: Case modification is a handy feature you can apply to a name or a title. Or is it? Case modification was an important aspect of the Bash 4 release. Bash version 4, RC1 would perform word splitting, and then case modification, resulting in title case (where every word is capitalized). It was decided to apply case modification to values, not words, for the Bash 4 release. Thanks Chet.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#case-modification-arrays","title":"Case modification: Arrays","text":"<p>Case modification can be used to create the proper capitalization for names or titles. Just assign it to an array:</p> <p><code>declare -a title=(my hello world john smith)</code></p> <p>For array expansion, the case modification applies to every expanded element, no matter if you expand an individual index or mass-expand the whole array using <code>@</code> or <code>*</code> subscripts. Some examples:</p> <p>Assume: <code>array=(This is some Text)</code></p> <ul> <li><code>echo \"${array[@],}\"</code><ul> <li>=&gt; <code>this is some text</code></li> </ul> </li> <li><code>echo \"${array[@],,}\"</code><ul> <li>=&gt; <code>this is some text</code></li> </ul> </li> <li><code>echo \"${array[@]^}\"</code><ul> <li>=&gt; <code>This Is Some Text</code></li> </ul> </li> <li><code>echo \"${array[@]^^}\"</code><ul> <li>=&gt; <code>THIS IS SOME TEXT</code></li> </ul> </li> <li><code>echo \"${array[2]^^}\"</code><ul> <li>=&gt; <code>SOME</code></li> </ul> </li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#variable-name-expansion","title":"Variable name expansion","text":"<p><code>${!PREFIX*}</code></p> <p><code>${!PREFIX@}</code></p> <p>This expands to a list of all set variable names beginning with the string <code>PREFIX</code>. The elements of the list are separated by the first character in the <code>IFS</code>-variable ( by default). <p>This will show all defined variable names (not values!) beginning with \"BASH\":</p> <pre><code>$ echo ${!BASH*}\nBASH BASH_ARGC BASH_ARGV BASH_COMMAND BASH_LINENO BASH_SOURCE BASH_SUBSHELL BASH_VERSINFO BASH_VERSION\n</code></pre> <p>This list will also include array names.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#substring-removal","title":"Substring removal","text":"<p><code>${PARAMETER#PATTERN}</code></p> <p><code>${PARAMETER##PATTERN}</code></p> <p><code>${PARAMETER%PATTERN}</code></p> <p><code>${PARAMETER%%PATTERN}</code></p> <p>This one can expand only a part of a parameter's value, given a pattern to describe what to remove from the string. The pattern is interpreted just like a pattern to describe a filename to match (globbing). See Pattern matching for more.</p> <p>Example string (just a quote from a big man):</p> <pre><code>MYSTRING=\"Be liberal in what you accept, and conservative in what you send\"\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#from-the-beginning","title":"From the beginning","text":"<p><code>${PARAMETER#PATTERN}</code> and <code>${PARAMETER##PATTERN}</code></p> <p>This form is to remove the described pattern trying to match it from the beginning of the string. The operator \"<code>#</code>\" will try to remove the shortest text matching the pattern, while \"<code>##</code>\" tries to do it with the longest text matching. Look at the following examples to get the idea (matched text ~~marked striked~~, remember it will be removed!):</p> Syntax Result <code>${MYSTRING#*in}</code> ~~Be liberal in~~ what you accept, and conservative in what you send <code>${MYSTRING##*in}</code> ~~Be liberal in what you accept, and conservative in~~ what you send","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#from-the-end","title":"From the end","text":"<p><code>${PARAMETER%PATTERN}</code> and <code>${PARAMETER%%PATTERN}</code></p> <p>In the second form everything will be the same, except that Bash now tries to match the pattern from the end of the string:</p> Syntax Result <code>${MYSTRING%in*}</code> Be liberal in what you accept, and conservative ~~in what you send~~ <code>${MYSTRING%%in*}</code> Be liberal ~~in what you accept, and conservative in what you send~~ <p>The second form nullifies variables that begin with <code>in</code>, by working from the end.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#common-use","title":"Common use","text":"<p>How the heck does that help to make my life easier?</p> <p>Well, maybe the most common use for it is to extract parts of a filename. Just look at the following list with examples:</p> <ul> <li>Get name without extension<ul> <li><code>${FILENAME%.*}</code></li> <li>=&gt; <code>bash_hackers.txt</code></li> </ul> </li> <li>Get extension<ul> <li><code>${FILENAME##*.}</code></li> <li>=&gt; <code>bash_hackers.txt</code></li> </ul> </li> <li>Get directory name<ul> <li><code>${PATHNAME%/*}</code></li> <li>=&gt; <code>/home/bash/bash_hackers.txt</code></li> </ul> </li> <li>Get filename<ul> <li><code>${PATHNAME##*/}</code></li> <li>=&gt; <code>/home/bash/bash_hackers.txt</code></li> </ul> </li> </ul> <p>These are the syntaxes for filenames with a single extension. Depending on your needs, you might need to adjust shortest/longest match.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#substring-removal-arrays","title":"Substring removal: Arrays","text":"<p>As for most parameter expansion features, working on arrays will handle each expanded element, for individual expansion and also for mass expansion.</p> <p>Simple example, removing a trailing <code>is</code> from all array elements (on expansion):</p> <p>Assume: <code>array=(This is a text)</code></p> <ul> <li><code>echo \"${array[@]%is}\"</code><ul> <li>=&gt; <code>Th a text</code></li> <li>(it was: <code>This is a text</code>)</li> </ul> </li> </ul> <p>All other variants of this expansion behave the same.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#search-and-replace","title":"Search and replace","text":"<p><code>${PARAMETER/PATTERN/STRING}</code></p> <p><code>${PARAMETER//PATTERN/STRING}</code></p> <p><code>${PARAMETER/PATTERN}</code></p> <p><code>${PARAMETER//PATTERN}</code></p> <p>This one can substitute (replace) a substring matched by a pattern, on expansion time. The matched substring will be entirely removed and the given string will be inserted. Again some example string for the tests:</p> <pre><code>MYSTRING=\"Be liberal in what you accept, and conservative in what you send\"\n</code></pre> <p>The two main forms only differ in the number of slashes after the parameter name: <code>${PARAMETER/PATTERN/STRING}</code> and <code>${PARAMETER//PATTERN/STRING}</code></p> <p>The first one (one slash) is to only substitute the first occurrence of the given pattern, the second one (two slashes) is to substitute all occurrences of the pattern.</p> <p>First, let's try to say \"happy\" instead of \"conservative\" in our example string:</p> <pre><code>${MYSTRING//conservative/happy}\n</code></pre> <p>=&gt; <code>Be liberal in what you accept, and conservativehappy in what you send</code></p> <p>Since there is only one \"conservative\" in that example, it really doesn't matter which of the two forms we use.</p> <p>Let's play with the word \"in\", I don't know if it makes any sense, but let's substitute it with \"by\".</p> <p>First form: Substitute first occurrence</p> <pre><code>${MYSTRING/in/by}\n</code></pre> <p><code>Be liberal inby what you accept, and conservative by what you send</code></p> <p>Second form: Substitute all occurrences</p> <pre><code>${MYSTRING//in/by}\n</code></pre> <p>=&gt; <code>Be liberal inby what you accept, and conservative inby what you send</code></p> <p>Anchoring Additionally you can \"anchor\" an expression: A <code>#</code> (hashmark) will indicate that your expression is matched against the beginning portion of the string, a <code>%</code> (percent-sign) will do it for the end portion.</p> <pre><code>MYSTRING=xxxxxxxxxx\necho ${MYSTRING/#x/y} # RESULT: yxxxxxxxxx\necho ${MYSTRING/%x/y} # RESULT: xxxxxxxxxy\n</code></pre> <p>If the replacement part is completely omitted, the matches are replaced by the nullstring, i.e., they are removed. This is equivalent to specifying an empty replacement:</p> <pre><code>echo ${MYSTRING//conservative/}\n# is equivalent to\necho ${MYSTRING//conservative}\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#search-and-replace-arrays","title":"Search and replace: Arrays","text":"<p>This parameter expansion type applied to arrays applies to all expanded elements, no matter if an individual element is expanded, or all elements using the mass expansion syntaxes.</p> <p>A simple example, changing the (lowercase) letter <code>t</code> to <code>d</code>:</p> <p>Assume: <code>array=(This is a text)</code></p> <ul> <li><code>echo \"${array[@]/t/d}\"</code><ul> <li>=&gt; <code>This is a dext</code></li> </ul> </li> <li><code>echo \"${array[@]//t/d}\"</code><ul> <li>=&gt; <code>This is a dexd</code></li> </ul> </li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#string-length","title":"String length","text":"<p><code>${#PARAMETER}</code></p> <p>When you use this form, the length of the parameter's value is expanded. Again, a quote from a big man, to have a test text:</p> <pre><code>MYSTRING=\"Be liberal in what you accept, and conservative in what you send\"\n</code></pre> <p>Using echo <code>${#MYSTRING}</code>...</p> <p>=&gt; <code>64</code></p> <p>The length is reported in characters, not in bytes. Depending on your environment this may not always be the same (multibyte-characters, like in UTF8 encoding).</p> <p>There's not much to say about it, mh?</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#string-length-arrays","title":"(String) length: Arrays","text":"<p>For arrays, this expansion type has two meanings:</p> <ul> <li>For individual elements, it reports the string length of the element (as for every \"normal\" parameter)</li> <li>For the mass subscripts <code>@</code> and <code>*</code> it reports the number of set elements in the array</li> </ul> <p>Example:</p> <p>Assume: <code>array=(This is a text)</code></p> <ul> <li><code>echo ${#array[1]}</code><ul> <li>=&gt; 2 (the word \"is\" has a length of 2)</li> </ul> </li> <li><code>echo ${#array[@]}</code><ul> <li>=&gt; 4 (the array contains 4 elements)</li> </ul> </li> </ul> <p>Attention: The number of used elements does not need to conform to the highest index. Sparse arrays are possible in Bash, that means you can have 4 elements, but with indexes 1, 7, 20, 31. You can't loop through such an array with a counter loop based on the number of elements!</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#substring-expansion","title":"Substring expansion","text":"<p><code>${PARAMETER:OFFSET}</code></p> <p><code>${PARAMETER:OFFSET:LENGTH}</code></p> <p>This one can expand only a part of a parameter's value, given a position to start and maybe a length. If <code>LENGTH</code> is omitted, the parameter will be expanded up to the end of the string. If <code>LENGTH</code> is negative, it's taken as a second offset into the string, counting from the end of the string.</p> <p><code>OFFSET</code> and <code>LENGTH</code> can be any arithmetic expression. Take care: The <code>OFFSET</code> starts at 0, not at 1!</p> <p>Example string (a quote from a big man): <code>MYSTRING=\"Be liberal in what you accept, and conservative in what you send\"</code></p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#using-only-offset","title":"Using only Offset","text":"<p>In the first form, the expansion is used without a length value, note that the offset 0 is the first character:</p> <pre><code>echo ${MYSTRING:35}\n</code></pre> <p>=&gt; <code>Be liberal in what you accept, and conservative in what you send</code></p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#using-offset-and-length","title":"Using Offset and Length","text":"<p>In the second form we also give a length value:</p> <pre><code>echo ${MYSTRING:35:12}\n</code></pre> <p>=&gt; <code>Be liberal in what you accept, and conservative in what you send</code></p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#negative-offset-value","title":"Negative Offset Value","text":"<p>If the given offset is negative, it's counted from the end of the string, i.e. an offset of -1 is the last character. In that case, the length still counts forward, of course. One special thing is to do when using a negative offset: You need to separate the (negative) number from the colon:</p> <pre><code>${MYSTRING: -10:5}\n${MYSTRING:(-10):5}\n</code></pre> <p>Why? Because it's interpreted as the parameter expansion syntax to use a default value.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#negative-length-value","title":"Negative Length Value","text":"<p>If the <code>LENGTH</code> value is negative, it's used as offset from the end of the string. The expansion happens from the first to the second offset then:</p> <pre><code>echo \"${MYSTRING:11:-17}\"\n</code></pre> <p>=&gt; <code>Be liberal in what you accept, and conservative in what you send</code></p> <p>This works since Bash 4.2-alpha, see also bashchanges.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#substringelement-expansion-arrays","title":"Substring/Element expansion: Arrays","text":"<p>For arrays, this expansion type has again 2 meanings:</p> <ul> <li>For individual elements, it expands to the specified substring (as for every \"normal\" parameter)</li> <li>For the mass subscripts <code>@</code> and <code>*</code> it mass-expands individual array elements denoted by the 2 numbers given (starting element, number of elements)</li> </ul> <p>Example:</p> <p>Assume: <code>array=(This is a text)</code></p> <ul> <li><code>echo ${array[0]:2:2}</code><ul> <li>=&gt; <code>is</code> (the \"is\" in \"This\", array element 0)</li> </ul> </li> <li><code>echo ${array[@]:1:2}</code><ul> <li>=&gt; <code>is a</code> (from element 1 inclusive, 2 elements are expanded, i.e. element 1 and 2)</li> </ul> </li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#use-a-default-value","title":"Use a default value","text":"<p><code>${PARAMETER:-WORD}</code></p> <p><code>${PARAMETER-WORD}</code></p> <p>If the parameter <code>PARAMETER</code> is unset (never was defined) or null (empty), this one expands to <code>WORD</code>, otherwise it expands to the value of <code>PARAMETER</code>, as if it just was <code>${PARAMETER}</code>. If you omit the <code>:</code> (colon), like shown in the second form, the default value is only used when the parameter was unset, not when it was empty.</p> <pre><code>echo \"Your home directory is: ${HOME:-/home/$USER}.\"\necho \"${HOME:-/home/$USER} will be used to store your personal data.\"\n</code></pre> <p>If <code>HOME</code> is unset or empty, everytime you want to print something useful, you need to put that parameter syntax in.</p> <pre><code>#!/bin/bash\n\nread -p \"Enter your gender (just press ENTER to not tell us): \" GENDER\necho \"Your gender is ${GENDER:-a secret}.\"\n</code></pre> <p>It will print \"Your gender is a secret.\" when you don't enter the gender. Note that the default value is used on expansion time, it is not assigned to the parameter.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#use-a-default-value-arrays","title":"Use a default value: Arrays","text":"<p>For arrays, the behaviour is very similar. Again, you have to make a difference between expanding an individual element by a given index and mass-expanding the array using the <code>@</code> and <code>*</code> subscripts.</p> <ul> <li>For individual elements, it's the very same: If the expanded element is <code>NULL</code> or unset (watch the <code>:-</code> and <code>-</code> variants), the default text is expanded</li> <li>For mass-expansion syntax, the default text is expanded if the array<ul> <li>contains no element or is unset (the <code>:-</code> and <code>-</code> variants mean the same here)</li> <li>contains only elements that are the nullstring (the <code>:-</code> variant)</li> </ul> </li> </ul> <p>In other words: The basic meaning of this expansion type is applied as consistent as possible to arrays.</p> <p>Example code (please try the example cases yourself):</p> <pre><code>####\n# Example cases for unset/empty arrays and nullstring elements\n####\n\n\n### CASE 1: Unset array (no array)\n\n# make sure we have no array at all\nunset array\n\necho ${array[@]:-This array is NULL or unset}\necho ${array[@]-This array is NULL or unset}\n\n### CASE 2: Set but empty array (no elements)\n\n# declare an empty array\narray=()\n\necho ${array[@]:-This array is NULL or unset}\necho ${array[@]-This array is NULL or unset}\n\n\n### CASE 3: An array with only one element, a nullstring\narray=(\"\")\n\necho ${array[@]:-This array is NULL or unset}\necho ${array[@]-This array is NULL or unset}\n\n\n### CASE 4: An array with only two elements, a nullstring and a normal word\narray=(\"\" word)\n\necho ${array[@]:-This array is NULL or unset}\necho ${array[@]-This array is NULL or unset}\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#assign-a-default-value","title":"Assign a default value","text":"<p><code>${PARAMETER:=WORD}</code></p> <p><code>${PARAMETER=WORD}</code></p> <p>This one works like the using default values, but the default text you give is not only expanded, but also assigned to the parameter, if it was unset or null. Equivalent to using a default value, when you omit the <code>:</code> (colon), as shown in the second form, the default value will only be assigned when the parameter was unset.</p> <pre><code>echo \"Your home directory is: ${HOME:=/home/$USER}.\"\necho \"$HOME will be used to store your personal data.\"\n</code></pre> <p>After the first expansion here (<code>${HOME:=/home/$USER}</code>), <code>HOME</code> is set and usable.</p> <p>Let's change our code example from above:</p> <pre><code>#!/bin/bash\n\nread -p \"Enter your gender (just press ENTER to not tell us): \" GENDER\necho \"Your gender is ${GENDER:=a secret}.\"\necho \"Ah, in case you forgot, your gender is really: $GENDER\"\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#assign-a-default-value-arrays","title":"Assign a default value: Arrays","text":"<p>For arrays this expansion type is limited. For an individual index, it behaves like for a \"normal\" parameter, the default value is assigned to this one element. The mass-expansion subscripts <code>@</code> and <code>*</code> can not be used here because it's not possible to assign to them!</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#use-an-alternate-value","title":"Use an alternate value","text":"<p><code>${PARAMETER:+WORD}</code></p> <p><code>${PARAMETER+WORD}</code></p> <p>This form expands to nothing if the parameter is unset or empty. If it is set, it does not expand to the parameter's value, but to some text you can specify:</p> <pre><code>echo \"The Java application was installed and can be started.${JAVAPATH:+ NOTE: JAVAPATH seems to be set}\"\n</code></pre> <p>The above code will simply add a warning if <code>JAVAPATH</code> is set (because it could influence the startup behaviour of that imaginary application).</p> <p>Some more unrealistic example... Ask for some flags (for whatever reason), and then, if they were set, print a warning and also print the flags:</p> <pre><code>#!/bin/bash\n\nread -p \"If you want to use special flags, enter them now: \" SPECIAL_FLAGS\necho \"The installation of the application is finished${SPECIAL_FLAGS:+ (NOTE: there are special flags set: $SPECIAL_FLAGS)}.\"\n</code></pre> <p>If you omit the colon, as shown in the second form (<code>${PARAMETER+WORD}</code>), the alternate value will be used if the parameter is set (and it can be empty)! You can use it, for example, to complain if variables you need (and that can be empty) are undefined:</p> <pre><code># test that with the three stages:\n\n# unset foo\n# foo=\"\"\n# foo=\"something\"\n\nif [[ ${foo+isset} = isset ]]; then\n echo \"foo is set...\"\nelse\n echo \"foo is not set...\"\nfi\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#use-an-alternate-value-arrays","title":"Use an alternate value: Arrays","text":"<p>Similar to the cases for arrays to expand to a default value, this expansion behaves like for a \"normal\" parameter when using individual array elements by index, but reacts differently when using the mass-expansion subscripts <code>@</code> and <code>*</code>:</p> <pre><code> * For individual elements, it's the very same: If the expanded element is **not** NULL or unset (watch the :+ and + variants), the alternate text is expanded\n * For mass-expansion syntax, the alternate text is expanded if the array\n * contains elements where min. one element is **not** a nullstring (the :+ and + variants mean the same here)\n * contains **only** elements that are **not** the nullstring (the :+ variant)\n</code></pre> <p>For some cases to play with, please see the code examples in the description for using a default value.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#display-error-if-null-or-unset","title":"Display error if null or unset","text":"<p><code>${PARAMETER:?WORD}</code></p> <p><code>${PARAMETER?WORD}</code></p> <p>If the parameter <code>PARAMETER</code> is set/non-null, this form will simply expand it. Otherwise, the expansion of <code>WORD</code> will be used as appendix for an error message:</p> <pre><code>$ echo \"The unset parameter is: ${p_unset?not set}\"\nbash: p_unset: not set\n</code></pre> <p>After printing this message,</p> <ul> <li>an interactive shell has <code>$?</code> to a non-zero value</li> <li>a non-interactive shell exits with a non-zero exit code</li> </ul> <p>The meaning of the colon (<code>:</code>) is the same as for the other parameter expansion syntaxes: It specifies if</p> <ul> <li>only unset or</li> <li>unset and empty parameters</li> </ul> <p>are taken into account.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#code-examples","title":"Code examples","text":"","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#substring-removal_1","title":"Substring removal","text":"<p>Removing the first 6 characters from a text string:</p> <pre><code>STRING=\"Hello world\"\n\n# only print 'Hello'\necho \"${STRING%??????}\"\n\n# only print 'world'\necho \"${STRING#??????}\"\n\n# store it into the same variable\nSTRING=${STRING#??????}\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#bugs-and-portability-considerations","title":"Bugs and Portability considerations","text":"<ul> <li> <p>Fixed in 4.2.36 (patch). Bash doesn't follow either POSIX or its own documentation when expanding either a quoted <code>\"$@\"</code> or <code>\"${arr[@]}\"</code> with an adjacent expansion. <code>\"$@$x\"</code> expands in the same way as <code>\"$*$x\"</code> - i.e. all parameters plus the adjacent expansion are concatenated into a single argument. As a workaround, each expansion needs to be quoted separately. Unfortunately, this bug took a very long time to notice. <code>~ $ set -- a b c; x=foo; printf '&lt;%s&gt; ' \"$@$x\" \"$*\"\"$x\" \"$@\"\"$x\" &lt;a b cfoo&gt; &lt;a b cfoo&gt; &lt;a&gt; &lt;b&gt; &lt;cfoo&gt;</code></p> </li> <li> <p>Almost all shells disagree about the treatment of an unquoted <code>$@</code>, <code>${arr[@]}</code>, <code>$*</code>, and <code>${arr[*]}</code> when IFS is set to null. POSIX is unclear about the expected behavior. A null IFS causes both word splitting and pathname expansion to behave randomly. Since there are few good reasons to leave <code>IFS</code> set to null for more than the duration of a command or two, and even fewer to expand <code>$@</code> and <code>$*</code> unquoted, this should be a rare issue. Always quote them! <pre><code>touch x 'y z'\nfor sh in bb {{d,b}a,{m,}k,z}sh; do\n echo \"$sh\"\n \"$sh\" -s a 'b c' d \\* &lt;/dev/fd/0\ndone &lt;&lt;\\EOF\n${ZSH_VERSION+:} false &amp;&amp; emulate sh\nIFS=\nprintf '&lt;%s&gt; ' $*\necho\nprintf \"&lt;%s&gt; \" $@\necho\nEOF\n</code></pre> <pre><code>bb\n&lt;ab cd*&gt;\n&lt;ab cd*&gt;\ndash\n&lt;ab cd*&gt;\n&lt;ab cd*&gt;\nbash\n&lt;a&gt; &lt;b c&gt; &lt;d&gt; &lt;x&gt; &lt;y z&gt;\n&lt;a&gt; &lt;b c&gt; &lt;d&gt; &lt;x&gt; &lt;y z&gt;\nmksh\n&lt;a b c d *&gt;\n&lt;a b c d *&gt;\nksh\n&lt;a&gt; &lt;b c&gt; &lt;d&gt; &lt;x&gt; &lt;y z&gt;\n&lt;a&gt; &lt;b c&gt; &lt;d&gt; &lt;x&gt; &lt;y z&gt;\nzsh\n&lt;a&gt; &lt;b c&gt; &lt;d&gt; &lt;x&gt; &lt;y z&gt;\n&lt;a&gt; &lt;b c&gt; &lt;d&gt; &lt;x&gt; &lt;y z&gt;\n</code></pre> When <code>IFS</code> is set to a non-null value, or unset, all shells behave the same - first expanding into separate args, then applying pathname expansion and word-splitting to the results, except for zsh, which doesn't do pathname expansion in its default mode.</p> </li> <li> <p>Additionally, shells disagree about various wordsplitting behaviors, the behavior of inserting delimiter characters from IFS in <code>$*</code>, and the way adjacent arguments are concatenated, when IFS is modified in the middle of expansion through side-effects. <pre><code>for sh in bb {{d,b}a,po,{m,}k,z}sh; do\n printf '%-4s: ' \"$sh\"\n \"$sh\" &lt;/dev/fd/0\ndone &lt;&lt;\\EOF\n${ZSH_VERSION+:} false &amp;&amp; emulate sh\nset -f -- a b c\nunset -v IFS\nprintf '&lt;%s&gt; ' ${*}${IFS=}${*}${IFS:=-}\"${*}\"\necho\nEOF\n</code></pre> <pre><code>bb : &lt;a b cabc&gt; &lt;a-b-c&gt;\ndash: &lt;a b cabc&gt; &lt;a-b-c&gt;\nbash: &lt;a&gt; &lt;b&gt; &lt;ca&gt; &lt;b&gt; &lt;c-a b c&gt;\nposh: &lt;a&gt; &lt;b&gt; &lt;ca b c&gt; &lt;a-b-c&gt;\nmksh: &lt;a&gt; &lt;b&gt; &lt;ca b c&gt; &lt;a-b-c&gt;\nksh : &lt;a&gt; &lt;b&gt; &lt;ca&gt; &lt;b&gt; &lt;c&gt; &lt;a b c&gt;\nzsh : &lt;a&gt; &lt;b&gt; &lt;ca&gt; &lt;b&gt; &lt;c&gt; &lt;a-b-c&gt;\n</code></pre> ksh93 and mksh can additionally achieve this side effect (and others) via the <code>${ cmds;}</code> expansion. I haven't yet tested every possible side-effect that can affect expansion halfway through expansion that way.</p> </li> <li> <p>As previously mentioned, the Bash form of indirection by prefixing a parameter expansion with a <code>!</code> conflicts with the same syntax used by mksh, zsh, and ksh93 for a different purpose. Bash will \"slightly\" modify this expansion in the next version with the addition of namerefs.</p> </li> <li> <p>Bash (and most other shells) don't allow .'s in identifiers. In ksh93, dots in variable names are used to reference methods (i.e. \"Discipline Functions\"), attributes, special shell variables, and to define the \"real value\" of an instance of a class.</p> </li> <li> <p>In ksh93, the <code>_</code> parameter has even more uses. It is used in the same way as <code>self</code> in some object-oriented languages; as a placeholder for some data local to a class; and also as the mechanism for class inheritance. In most other contexts, <code>_</code> is compatible with Bash.</p> </li> <li> <p>Bash only evaluates the subscripts of the slice expansion (<code>${x:y:z}</code>) if the parameter is set (for both nested expansions and arithmetic). For ranges, Bash evaluates as little as possible, i.e., if the first part is out of range, the second won't be evaluated. ksh93 and mksh always evaluate the subscript parts even if the parameter is unset. <pre><code>$ bash -c 'n=\"y[\\$(printf yo &gt;&amp;2)1]\" m=\"y[\\$(printf jo &gt;&amp;2)1]\"; x=(); echo \"${x[@]:n,6:m}\"' # No output\n $ bash -c 'n=\"y[\\$(printf yo &gt;&amp;2)1]\" m=\"y[\\$(printf jo &gt;&amp;2)1]\"; x=([5]=hi); echo \"${x[@]:n,6:m}\"'\nyo\n $ bash -c 'n=\"y[\\$(printf yo &gt;&amp;2)1]\" m=\"y[\\$(printf jo &gt;&amp;2)1]\"; x=([6]=hi); echo \"${x[@]:n,6:m}\"'\nyojo\n $ bash -c 'n=\"y[\\$(printf yo &gt;&amp;2)1]\" m=\"y[\\$(printf jo &gt;&amp;2)1]\"; x=12345; echo \"${x:n,5:m}\"'\nyojo\n $ bash -c 'n=\"y[\\$(printf yo &gt;&amp;2)1]\" m=\"y[\\$(printf jo &gt;&amp;2)1]\"; x=12345; echo \"${x:n,6:m}\"'\nyo\n</code></pre></p> </li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#quote-nesting","title":"Quote Nesting","text":"<ul> <li>In most shells, when dealing with an \"alternate\" parameter expansion that expands to multiple words, and nesting such expansions, not all combinations of nested quoting are possible.</li> </ul> <pre><code># Bash\n $ typeset -a a=(meh bleh blerg) b\n $ IFS=e\n $ printf \"&lt;%s&gt; \" \"${b[@]-\"${a[@]}\" \"${a[@]}\"}\"; echo # The entire PE is quoted so Bash considers the inner quotes redundant.\n&lt;meh&gt; &lt;bleh&gt; &lt;blerg meh&gt; &lt;bleh&gt; &lt;blerg&gt;\n $ printf \"&lt;%s&gt; \" \"${b[@]-${a[@]} ${a[@]}}\"; echo # The outer quotes cause the inner expansions to be considered quoted.\n&lt;meh&gt; &lt;bleh&gt; &lt;blerg meh&gt; &lt;bleh&gt; &lt;blerg&gt;\n $ b=(meep beep)\n $ printf \"&lt;%s&gt; \" \"${b[@]-\"${a[@]}\" \"${a[@]}\"}\" \"${b[@]-${a[@]} ${a[@]}}\"; echo # Again no surprises. Outer quotes quote everything recursively.\n&lt;meep&gt; &lt;beep&gt; &lt;meep&gt; &lt;beep&gt;\n</code></pre> <p>Now lets see what can happen if we leave the outside unquoted.</p> <pre><code># Bash\n $ typeset -a a=(meh bleh blerg) b\n $ IFS=e\n $ printf \"&lt;%s&gt; \" ${b[@]-\"${a[@]}\" \"${a[@]}\"}; echo # Inner quotes make inner expansions quoted.\n&lt;meh&gt; &lt;bleh&gt; &lt;blerg meh&gt; &lt;bleh&gt; &lt;blerg&gt;\n $ printf \"&lt;%s&gt; \" ${b[@]-${a[@]} ${a[@]}}; echo' # No quotes at all wordsplits / globs, like you'd expect.\n&lt;m&gt; &lt;h&gt; &lt;bl&gt; &lt;h&gt; &lt;bl&gt; &lt;rg m&gt; &lt;h&gt; &lt;bl&gt; &lt;h&gt; &lt;bl&gt; &lt;rg&gt;\n</code></pre> <p>This all might be intuitive, and is the most common implementation, but this design sucks for a number of reasons. For one, it means Bash makes it absolutely impossible to expand any part of the inner region unquoted while leaving the outer region quoted. Quoting the outer forces quoting of the inner regions recursively (except nested command substitutions of course). Word-splitting is necessary to split words of the inner region, which cannot be done together with outer quoting. Consider the following (only slightly far-fetched) code:</p> <pre><code># Bash (non-working example)\n\nunset -v IFS # make sure we have a default IFS\n\nif some crap; then\n typeset -a someCmd=(myCmd arg1 'arg2 yay!' 'third*arg*' 4)\nfi\n\nsomeOtherCmd=mycommand\ntypeset -a otherArgs=(arg3 arg4)\n\n# What do you think the programmer expected to happen here?\n# What do you think will actually happen...\n\n\"${someCmd[@]-\"$someOtherCmd\" arg2 \"${otherArgs[@]}\"}\" arg5\n</code></pre> <p>This final line is perhaps not the most obvious, but I've run into cases were this type of logic can be desirable and realistic. We can deduce what was intended:</p> <ul> <li>If <code>someCmd</code> is set, then the resulting expansion should run the command: <code>\"myCmd\" \"arg1\" \"arg2 yay!\" \"third*arg*\" \"4\" \"arg5\"</code></li> <li>Otherwise, if <code>someCmd</code> is not set, expand <code>$someOtherCmd</code> and the inner args, to run a different command: <code>\"mycommand\" \"arg2\" \"arg3\" \"arg4\" \"arg5\"</code>.</li> </ul> <p>Unfortunately, it is impossible to get the intended result in Bash (and most other shells) without taking a considerably different approach. The only way to split the literal inner parts is through word-splitting, which requires that the PE be unquoted. But, the only way to expand the outer expansion correctly without word-splitting or globbing is to quote it. Bash will actually expand the command as one of these:</p> <pre><code># The quoted PE produces a correct result here...\n $ bash -c 'typeset -a someCmd=(myCmd arg1 \"arg2 yay!\" \"third*arg*\" 4); printf \"&lt;%s&gt; \" \"${someCmd[@]-\"$someOtherCmd\" arg2 \"${otherArgs[@]}\"}\" arg5; echo'\n&lt;myCmd&gt; &lt;arg1&gt; &lt;arg2 yay!&gt; &lt;third*arg*&gt; &lt;4&gt; &lt;arg5&gt;\n\n# ...but in the opposite case the first 3 arguments are glued together. There are no workarounds.\n $ bash -c 'typeset -a otherArgs=(arg3 arg4); someOtherCmd=mycommand; printf \"&lt;%s&gt; \" \"${someCmd[@]-\"$someOtherCmd\" arg2 \"${otherArgs[@]}\"}\" arg5; echo'\n&lt;mycommand arg2 arg3&gt; &lt;arg4&gt; &lt;arg5&gt;\n\n# UNLESS! we unquote the outer expansion allowing the inner quotes to\n# affect the necessary parts while allowing word-splitting to split the literals:\n $ bash -c 'typeset -a otherArgs=(arg3 arg4); someOtherCmd=mycommand; printf \"&lt;%s&gt; \" ${someCmd[@]-\"$someOtherCmd\" arg2 \"${otherArgs[@]}\"} arg5; echo'\n&lt;mycommand&gt; &lt;arg2&gt; &lt;arg3&gt; &lt;arg4&gt; &lt;arg5&gt;\n\n# Success!!!\n $ bash -c 'typeset -a someCmd=(myCmd arg1 \"arg2 yay!\" \"third*arg*\" 4); printf \"&lt;%s&gt; \" ${someCmd[@]-\"$someOtherCmd\" arg2 \"${otherArgs[@]}\"} arg5; echo'\n&lt;myCmd&gt; &lt;arg1&gt; &lt;arg2&gt; &lt;yay!&gt; &lt;third*arg*&gt; &lt;4&gt; &lt;arg5&gt;\n\n# ...Ah f^^k. (again, no workaround possible.)\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#the-ksh93-exception","title":"The ksh93 exception","text":"<p>To the best of my knowledge, ksh93 is the only shell that acts differently. Rather than forcing nested expansions into quoting, a quote at the beginning and end of the nested region will cause the quote state to reverse itself within the nested part. I have no idea whether it's an intentional or documented effect, but it does solve the problem and consequently adds a lot of potential power to these expansions.</p> <p>All we need to do is add two extra double-quotes:</p> <pre><code># ksh93 passing the two failed tests from above:\n\n $ ksh -c 'otherArgs=(arg3 arg4); someOtherCmd=\"mycommand\"; printf \"&lt;%s&gt; \" \"${someCmd[@]-\"\"$someOtherCmd\" arg2 \"${otherArgs[@]}\"\"}\" arg5; echo'\n&lt;mycommand&gt; &lt;arg2&gt; &lt;arg3&gt; &lt;arg4&gt; &lt;arg5&gt;\n\n $ ksh -c 'typeset -a someCmd=(myCmd arg1 \"arg2 yay!\" \"third*arg*\" 4); printf \"&lt;%s&gt; \" \"${someCmd[@]-\"\"$someOtherCmd\" arg2 \"${otherArgs[@]}\"\"}\" arg5; echo'\n&lt;myCmd&gt; &lt;arg1&gt; &lt;arg2 yay!&gt; &lt;third*arg*&gt; &lt;4&gt; &lt;arg5&gt;\n</code></pre> <p>This can be used to control the quote state of any part of any expansion to an arbitrary depth. Sadly, it is the only shell that does this and the difference may introduce a possible compatibility problem.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/pe/#see-also","title":"See also","text":"<ul> <li>Internal: Introduction to expansion and substitution</li> <li>Internal: Arrays</li> <li>Dictionary, internal: parameter</li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","variable","parameter","mangle","substitute","change","check","defined","null","array","arrays"]},{"location":"syntax/quoting/","title":"Quotes and escaping","text":"<p>Quoting and escaping are important, as they influence the way Bash acts upon your input. There are three recognized types:</p> <ul> <li>per-character escaping using a backslash: <code>\\$stuff</code></li> <li>weak quoting with double-quotes: <code>\"stuff\"</code></li> <li>strong quoting with single-quotes: <code>'stuff'</code></li> </ul> <p>All three forms have the very same purpose: They give you general control over parsing, expansion and expansion results.</p> <p>Besides these basic variants, there are some special quoting methods (like interpreting ANSI-C escapes in a string) you'll meet below.</p> <p>:!: ATTENTION :!: The quote characters (<code>\"</code>, double quote and <code>'</code>, single quote) are a syntax element that influence parsing. It is not related to the quote characters passed as text to the command line! The syntax quotes are removed before the command is called! Example:</p> <pre><code>### NO NO NO: this passes three strings:\n### (1) \"my\n### (2) multiword\n### (3) argument\"\nMYARG=\"\\\"my multiword argument\\\"\"\nsomecommand $MYARG\n\n### THIS IS NOT (!) THE SAME AS ###\ncommand \"my multiword argument\"\n\n### YOU NEED ###\nMYARG=\"my multiword argument\"\ncommand \"$MYARG\"\n</code></pre>","tags":["bash","shell","scripting","quoting","quotes","escape","backslash","marks","singlequotes","doublequotes","single","double"]},{"location":"syntax/quoting/#per-character-escaping","title":"Per-character escaping","text":"<p>Per-character escaping is useful in on expansions and substitutions. In general, a character that has a special meaning to Bash, like the dollar-sign (<code>$</code>) can be masked to not have a special meaning using the backslash:</p> <pre><code>echo \\$HOME is set to \\\"$HOME\\\"\n</code></pre> <ul> <li><code>\\$HOME</code> won't expand because it's not in variable-expansion syntax anymore</li> <li>The backslash changes the quotes into literals - otherwise Bash would interpret them</li> </ul> <p>The sequence <code>&lt;newline&gt;</code> (an unquoted backslash, followed by a <code>&lt;newline&gt;</code> character) is interpreted as line continuation. It is removed from the input stream and thus effectively ignored. Use it to beautify your code:</p> <pre><code># escapestr_sed()\n# read a stream from stdin and escape characters in text that could be interpreted as\n# special characters by sed\nescape_sed() {\n sed \\\n -e 's/\\//\\\\\\//g' \\\n -e 's/\\&amp;/\\\\\\&amp;/g'\n}\n</code></pre> <p>The backslash can be used to mask every character that has a special meaning to bash. Exception: Inside a single-quoted string (see below).</p>","tags":["bash","shell","scripting","quoting","quotes","escape","backslash","marks","singlequotes","doublequotes","single","double"]},{"location":"syntax/quoting/#weak-quoting","title":"Weak quoting","text":"<p>Inside a weak-quoted string there's no special interpretion of:</p> <ul> <li>spaces as word-separators (on inital command line splitting and on word splitting!)</li> <li>single-quotes to introduce strong-quoting (see below)</li> <li>characters for pattern matching</li> <li>tilde expansion</li> <li>pathname expansion</li> <li>process substitution</li> </ul> <p>Everything else, especially parameter expansion, is performed!</p> <pre><code>ls -l \"*\"\n</code></pre> <p>Will not be expanded. <code>ls</code> gets the literal <code>*</code> as argument. It will, unless you have a file named <code>*</code>, spit out an error.</p> <pre><code>echo \"Your PATH is: $PATH\"\n</code></pre> <p>Will work as expected. <code>$PATH</code> is expanded, because it's double (weak) quoted.</p> <p>If a backslash in double quotes (\"weak quoting\") occurs, there are 2 ways to deal with it</p> <ul> <li>if the baskslash is followed by a character that would have a special meaning even inside double-quotes, the backslash is removed and the following character looses its special meaning</li> <li>if the backslash is followed by a character without special meaning, the backslash is not removed</li> </ul> <p>In particuar this means that <code>\"\\$\"</code> will become <code>$</code>, but <code>\"\\x\"</code> will become <code>\\x</code>.</p>","tags":["bash","shell","scripting","quoting","quotes","escape","backslash","marks","singlequotes","doublequotes","single","double"]},{"location":"syntax/quoting/#strong-quoting","title":"Strong quoting","text":"<p>Strong quoting is very easy to explain:</p> <p>Inside a single-quoted string nothing is interpreted, except the single-quote that closes the string.</p> <pre><code>echo 'Your PATH is: $PATH'\n</code></pre> <p><code>$PATH</code> won't be expanded, it's interpreted as ordinary text because it's surrounded by strong quotes.</p> <p>In practise that means, to produce a text like <code>Here's my test...</code> as a single-quoted string, you have to leave and re-enter the single quoting to get the character \"<code>'</code>\" as literal text:</p> <pre><code># WRONG\necho 'Here's my test...'\n\n# RIGHT\necho 'Here'\\''s my test...'\n\n# ALTERNATIVE: It's also possible to mix-and-match quotes for readability:\necho \"Here's my test\"\n</code></pre>","tags":["bash","shell","scripting","quoting","quotes","escape","backslash","marks","singlequotes","doublequotes","single","double"]},{"location":"syntax/quoting/#ansi-c-like-strings","title":"ANSI C like strings","text":"<p>Bash provides another quoting mechanism: Strings that contain ANSI C-like escape sequences. The Syntax is:</p> <pre><code>$'string'\n</code></pre> <p>where the following escape sequences are decoded in <code>string</code>:</p> Code Meaning <code>\\\"</code> double-quote <code>\\'</code> single-quote <code>\\\\</code> backslash <code>\\a</code> terminal alert character (bell) <code>\\b</code> backspace <code>\\e</code> escape (ASCII 033) <code>\\E</code> escape (ASCII 033) \\E is non-standard <code>\\f</code> form feed <code>\\n</code> newline <code>\\r</code> carriage return <code>\\t</code> horizontal tab <code>\\v</code> vertical tab <code>\\cx</code> a control-x character, for example, <code>$'\\cZ'</code> to print the control sequence composed of Ctrl-Z (<code>^Z</code>) <code>\\uXXXX</code> Interprets <code>XXXX</code> as a hexadecimal number and prints the corresponding character from the character set (4 digits) (Bash 4.2-alpha) <code>\\UXXXXXXXX</code> Interprets <code>XXXX</code> as a hexadecimal number and prints the corresponding character from the character set (8 digits) (Bash 4.2-alpha) <code>\\nnn</code> the eight-bit character whose value is the octal value nnn (one to three digits) <code>\\xHH</code> the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) <p>This is especially useful when you want to pass special characters as arguments to some programs, like passing a newline to sed.</p> <p>The resulting text is treated as if it were single-quoted. No further expansion happens.</p> <p>The <code>$'...'</code> syntax comes from ksh93, but is portable to most modern shells including pdksh. A specification for it was accepted for SUS issue 7. There are still some stragglers, such as most ash variants including dash, (except busybox built with \"bash compatibility\" features).</p>","tags":["bash","shell","scripting","quoting","quotes","escape","backslash","marks","singlequotes","doublequotes","single","double"]},{"location":"syntax/quoting/#i18nl10n","title":"I18N/L10N","text":"<p>A dollar-sign followed by a double-quoted string, for example</p> <pre><code>echo $\"generating database...\"\n</code></pre> <p>means I18N. If there is a translation available for that string, it is used instead of the given text. If not, or if the locale is <code>C</code>/<code>POSIX</code>, the dollar sign is simply ignored, which results in a normal double quoted string.</p> <p>If the string was replaced (translated), the result is double quoted.</p> <p>In case you're a C programmer: The purpose of <code>$\"...\"</code> is the same as for <code>gettext()</code> or <code>_()</code>.</p> <p>For useful examples to localize your scripts, please see Appendix I of the Advanced Bash Scripting Guide.</p> <p>Attention: There is a security hole. Please read the gettext documentation</p>","tags":["bash","shell","scripting","quoting","quotes","escape","backslash","marks","singlequotes","doublequotes","single","double"]},{"location":"syntax/quoting/#common-mistakes","title":"Common mistakes","text":"","tags":["bash","shell","scripting","quoting","quotes","escape","backslash","marks","singlequotes","doublequotes","single","double"]},{"location":"syntax/quoting/#string-lists-in-for-loops","title":"String lists in for-loops","text":"<p>The classic for loop uses a list of words to iterate through. The list can also be in a variable:</p> <pre><code>mylist=\"DOG CAT BIRD HORSE\"\n</code></pre> <p>WRONG way to iterate through this list:</p> <pre><code>for animal in \"$mylist\"; do\n echo $animal\ndone\n</code></pre> <p>Why? Due to the double-quotes, technically, the expansion of <code>$mylist</code> is seen as one word. The for loop iterates exactly one time, with <code>animal</code> set to the whole list.</p> <p>RIGHT way to iterate through this list:</p> <pre><code>for animal in $mylist; do\n echo $animal\ndone\n</code></pre>","tags":["bash","shell","scripting","quoting","quotes","escape","backslash","marks","singlequotes","doublequotes","single","double"]},{"location":"syntax/quoting/#working-out-the-test-command","title":"Working out the test-command","text":"<p>The command <code>test</code> or <code>[ ... ]</code> (the classic test command) is an ordinary command, so ordinary syntax rules apply. Let's take string comparison as an example:</p> <pre><code>[ WORD = WORD ]\n</code></pre> <p>The <code>]</code> at the end is a convenience; if you type <code>which [</code> you will see that there is in fact a binary file with that name. So if we were writing this as a test command it would be:</p> <pre><code>test WORD = WORD\n</code></pre> <p>When you compare variables, it's wise to quote them. Let's create a test string with spaces:</p> <pre><code>mystring=\"my string\"\n</code></pre> <p>And now check that string against the word \"testword\":</p> <pre><code>[ $mystring = testword ] # WRONG!\n</code></pre> <p>This fails! These are too many arguments for the string comparison test. After expansion is performed, you really execute:</p> <pre><code>[ my string = testword ]\ntest my string = testword\n</code></pre> <p>Which is wrong, because <code>my</code> and <code>string</code> are two separate arguments.</p> <p>So what you really want to do is:</p> <pre><code>[ \"$mystring\" = testword ] # RIGHT!\n\ntest 'my string' = testword\n</code></pre> <p>Now the command has three parameters, which makes sense for a binary (two argument) operator.</p> <p>Hint: Inside the conditional expression (<code>[[ ]]</code>) Bash doesn't perform word splitting, and thus you don't need to quote your variable references - they are always seen as \"one word\".</p>","tags":["bash","shell","scripting","quoting","quotes","escape","backslash","marks","singlequotes","doublequotes","single","double"]},{"location":"syntax/quoting/#see-also","title":"See also","text":"<ul> <li>Internal: Some words about words...</li> <li>Internal: Word splitting</li> <li>Internal: Introduction to expansions and substitutions</li> <li>External: Grymore: Shellquoting</li> </ul>","tags":["bash","shell","scripting","quoting","quotes","escape","backslash","marks","singlequotes","doublequotes","single","double"]},{"location":"syntax/redirection/","title":"Redirection","text":"<p>FIXME</p> <p>To be continued</p> <p>Redirection makes it possible to control where the output of a command goes to, and where the input of a command comes from. It's a mighty tool that, together with pipelines, makes the shell powerful. The redirection operators are checked whenever a simple command is about to be executed.</p> <p>Under normal circumstances, there are 3 files open, accessible by the file descriptors 0, 1 and 2, all connected to your terminal:</p> Name FD Description <code>stdin</code> 0 standard input stream (e.g. keyboard) <code>stdout</code> 1 standard output stream (e.g. monitor) <code>stderr</code> 2 standard error output stream (usually also on monitor) <p>INFO</p> <p>The terms \"monitor\" and \"keyboard\" refer to the same device, the terminal here. Check your preferred UNIX\u00ae-FAQ for details, I'm too lazy to explain what a terminal is ;-)</p> <p>Both, <code>stdout</code> and <code>stderr</code> are output file descriptors. Their difference is the convention that a program outputs payload on <code>stdout</code> and diagnostic- and error-messages on <code>stderr</code>. If you write a script that outputs error messages, please make sure you follow this convention!</p> <p>Whenever you name such a filedescriptor, i.e. you want to redirect this descriptor, you just use the number:</p> <pre><code># this executes the cat-command and redirects its error messages (stderr) to the bit bucket\ncat some_file.txt 2&gt;/dev/null\n</code></pre> <p>Whenever you reference a descriptor, to point to its current target file, then you use a \"<code>&amp;</code>\" followed by a the descriptor number:</p> <pre><code># this executes the echo-command and redirects its normal output (stdout) to the standard error target\necho \"There was an error\" 1&gt;&amp;2\n</code></pre> <p>The redirection operation can be anywhere in a simple command, so these examples are equivalent:</p> <pre><code>cat foo.txt bar.txt &gt;new.txt\ncat &gt;new.txt foo.txt bar.txt\n&gt;new.txt cat foo.txt bar.txt\n</code></pre> <p>important</p> <p>Every redirection operator takes one or two words as operands. If you have to use operands (e.g. filenames to redirect to) that contain spaces you must quote them!</p>"},{"location":"syntax/redirection/#valid-redirection-targets-and-sources","title":"Valid redirection targets and sources","text":"<p>This syntax is recognized whenever a <code>TARGET</code> or a <code>SOURCE</code> specification (like below in the details descriptions) is used.</p> Syntax Description <code>FILENAME</code> references a normal, ordinary filename from the filesystem (which can of course be a FIFO, too. Simply everything you can reference in the filesystem) <code>&amp;N</code> references the current target/source of the filedescriptor <code>N</code> (\"duplicates\" the filedescriptor) <code>&amp;-</code> closes the redirected filedescriptor, useful instead of <code>&gt; /dev/null</code> constructs (<code>&gt; &amp;-</code>) <code>/dev/fd/N</code> duplicates the filedescriptor <code>N</code>, if <code>N</code> is a valid integer <code>/dev/stdin</code> duplicates filedescriptor 0 (<code>stdin</code>) <code>/dev/stdout</code> duplicates filedescriptor 1 (<code>stdout</code>) <code>/dev/stderr</code> duplicates filedescriptor 2 (<code>stderr</code>) <code>/dev/tcp/HOST/PORT</code> assuming <code>HOST</code> is a valid hostname or IP address, and <code>PORT</code> is a valid port number or service name: redirect from/to the corresponding TCP socket <code>/dev/udp/HOST/PORT</code> assuming <code>HOST</code> is a valid hostname or IP address, and <code>PORT</code> is a valid port number or service name: redirect from/to the corresponding UDP socket <p>If a target/source specification fails to open, the whole redirection operation fails. Avoid referencing file descriptors above 9, since you may collide with file descriptors Bash uses internally.</p>"},{"location":"syntax/redirection/#redirecting-output","title":"Redirecting output","text":"<pre><code>N &gt; TARGET\n</code></pre> <p>This redirects the file descriptor number <code>N</code> to the target <code>TARGET</code>. If <code>N</code> is omitted, <code>stdout</code> is assumed (FD 1). The <code>TARGET</code> is truncated before writing starts.</p> <p>If the option <code>noclobber</code> is set with the set builtin, with cause the redirection to fail, when <code>TARGET</code> names a regular file that already exists. You can manually override that behaviour by forcing overwrite with the redirection operator <code>&gt;|</code> instead of <code>&gt;</code>.</p>"},{"location":"syntax/redirection/#appending-redirected-output","title":"Appending redirected output","text":"<pre><code>N &gt;&gt; TARGET\n</code></pre> <p>This redirects the file descriptor number <code>N</code> to the target <code>TARGET</code>. If <code>N</code> is omitted, <code>stdout</code> is assumed (FD 1). The <code>TARGET</code> is not truncated before writing starts.</p>"},{"location":"syntax/redirection/#redirecting-output-and-error-output","title":"Redirecting output and error output","text":"<pre><code>&amp;&gt; TARGET\n\n&gt;&amp; TARGET\n</code></pre> <p>This special syntax redirects both, <code>stdout</code> and <code>stderr</code> to the specified target. It's equivalent to</p> <pre><code>&gt; TARGET 2&gt;&amp;1\n</code></pre> <p>Since Bash4, there's <code>&amp;&gt;&gt;TARGET</code>, which is equivalent to <code>&gt;&gt; TARGET 2&gt;&amp;1</code>.</p> <p>important</p> <p>This syntax is deprecated and should not be used. See the page about obsolete and deprecated syntax.</p>"},{"location":"syntax/redirection/#appending-redirected-output-and-error-output","title":"Appending redirected output and error output","text":"<p>To append the cumulative redirection of <code>stdout</code> and <code>stderr</code> to a file you simply do</p> <pre><code>&gt;&gt; FILE 2&gt;&amp;1\n\n&amp;&gt;&gt; FILE\n</code></pre>"},{"location":"syntax/redirection/#transporting-stdout-and-stderr-through-a-pipe","title":"Transporting stdout and stderr through a pipe","text":"<pre><code>COMMAND1 2&gt;&amp;1 | COMMAND2\n\nCOMMAND1 |&amp; COMMAND2\n</code></pre>"},{"location":"syntax/redirection/#redirecting-input","title":"Redirecting input","text":"<pre><code>N &lt; SOURCE\n</code></pre> <p>The input descriptor <code>N</code> uses <code>SOURCE</code> as its data source. If <code>N</code> is omitted, filedescriptor 0 (<code>stdin</code>) is assumed.</p>"},{"location":"syntax/redirection/#here-documents","title":"Here documents","text":"<p> <pre><code>&lt;&lt;TAG\n...\nTAG\n\n&lt;&lt;-TAG\n...\nTAG\n</code></pre> <p>A here-document is an input redirection using source data specified directly at the command line (or in the script), no \"external\" source. The redirection-operator <code>&lt;&lt;</code> is used together with a tag <code>TAG</code> that's used to mark the end of input later:</p> <pre><code># display help\n\ncat &lt;&lt;EOF\nSorry...\nNo help available yet for $PROGRAM.\nHehe...\nEOF\n</code></pre> <p>As you see, substitutions are possible. To be precise, the following substitutions and expansions are performed in the here-document data:</p> <ul> <li>Parameter expansion</li> <li>Command substitution</li> <li>Arithmetic expansion</li> </ul> <p>You can avoid that by quoting the tag:</p> <pre><code>cat &lt;&lt;\"EOF\"\nThis won't be expanded: $PATH\nEOF\n</code></pre> <p>Last but not least, if the redirection operator <code>&lt;&lt;</code> is followed by a <code>-</code> (dash), all leading TAB from the document data will be ignored. This might be useful to have optical nice code also when using here-documents.</p> <p>The tag you use must be the only word in the line, to be recognized as end-of-here-document marker.</p> <p>info</p> <p>It seems that here-documents (tested on versions <code>1.14.7</code>, <code>2.05b</code> and <code>3.1.17</code>) are correctly terminated when there is an EOF before the end-of-here-document tag. The reason is unknown, but it seems to be done on purpose. Bash 4 introduced a warning message when end-of-file is seen before the tag is reached.</p>"},{"location":"syntax/redirection/#here-strings","title":"Here strings","text":"<pre><code>&lt;&lt;&lt; WORD\n</code></pre> <p>The here-strings are a variation of the here-documents. The word <code>WORD</code> is taken for the input redirection:</p> <pre><code>cat &lt;&lt;&lt; \"Hello world... $NAME is here...\"\n</code></pre> <p>Just beware to quote the <code>WORD</code> if it contains spaces. Otherwise the rest will be given as normal parameters.</p> <p>The here-string will append a newline (<code>\\n</code>) to the data.</p>"},{"location":"syntax/redirection/#multiple-redirections","title":"Multiple redirections","text":"<p>More redirection operations can occur in a line of course. The order is important! They're evaluated from left to right. If you want to redirect both, <code>stderr</code> and <code>stdout</code> to the same file (like <code>/dev/null</code>, to hide it), this is the wrong way:</p> <pre><code># { echo OUTPUT; echo ERRORS &gt;&amp;2; } is to simulate something that outputs to STDOUT and STDERR\n# you can test with it\n{ echo OUTPUT; echo ERRORS &gt;&amp;2; } 2&gt;&amp;1 1&gt;/dev/null\n</code></pre> <p>Why? Relatively easy:</p> <ul> <li>initially, <code>stdout</code> points to your terminal (you read it)</li> <li>same applies to <code>stderr</code>, it's connected to your terminal</li> <li><code>2&gt;&amp;1</code> redirects <code>stderr</code> away from the terminal to the target for <code>stdout</code>: the terminal (again...)</li> <li><code>1&gt;/dev/null</code> redirects <code>stdout</code> away from your terminal to the file <code>/dev/null</code></li> </ul> <p>What remains? <code>stdout</code> goes to <code>/dev/null</code>, <code>stderr</code> still (or better: \"again\") goes to the terminal. You have to swap the order to make it do what you want:</p> <pre><code>{ echo OUTPUT; echo ERRORS &gt;&amp;2; } 1&gt;/dev/null 2&gt;&amp;1\n</code></pre>"},{"location":"syntax/redirection/#examples","title":"Examples","text":"<p>How to make a program quiet (assuming all output goes to <code>STDOUT</code> and <code>STDERR</code>?</p> <pre><code>command &gt;/dev/null 2&gt;&amp;1\n</code></pre>"},{"location":"syntax/redirection/#see-also","title":"See also","text":"<ul> <li>Internal: Illustrated Redirection Tutorial</li> <li>Internal: The noclobber option</li> <li>Internal: The exec builtin command</li> <li>Internal: Simple commands parsing and execution</li> <li>Internal: Process substitution syntax</li> <li>Internal: Obsolete and deprecated syntax</li> <li>Internal: Nonportable syntax and command uses</li> </ul>"},{"location":"syntax/shellvars/","title":"Special parameters and shell variables","text":""},{"location":"syntax/shellvars/#special-parameters","title":"Special Parameters","text":"parameter character expansion description <code>*</code> asterisk The positional parameters starting from the first. When used inside doublequotes (see quoting), like <code>\"$*\"</code>, it expands to all positional parameters as one word, delimited by the first character of the <code>IFS</code> variable (a space in this example): <code>\"$1 $2 $3 $4\"</code>.If <code>IFS</code> is unset, the delimiter used will be always a space, if <code>IFS</code> is NULL, the delimiter will be nothing, which effectively concatenates all the positional parameters without any delimiter.When used unquoted, it will just expand to the strings, one by one, not preserving the word boundaries (i.e. word splitting will split the text again, if it contains <code>IFS</code> characters.See also the scripting article about handling positional parameters. <code>@</code> at-sign The positional parameters starting from the first. When used inside doublequotes (see quoting), like <code>\"$@\"</code>, it expands all positional parameters as separate words: <code>\"$1\" \"$2\" \"$3\" \"$4\"</code>Without doublequotes, the behaviour is like the one of <code>*</code> without doublequotes.See also the scripting article about handling positional parameters. <code>#</code> hash mark Number of positional parameters (decimal)See also the scripting article about handling positional parameters. <code>?</code> question mark Status of the most recently executed foreground-pipeline (exit/return code) <code>-</code> dash Current option flags set by the shell itself, on invocation, or using the set builtin command. It\\'s just a set of characters, like <code>himB</code> for <code>h</code>, <code>i</code>, <code>m</code> and <code>B</code>. <code>$</code> dollar-sign The process ID (PID) of the shell. In an explicit subshell it expands to the PID of the current \\\"main shell\\\", not the subshell. This is different from <code>$BASHPID</code>! <code>!</code> exclamation mark The process ID (PID) of the most recently executed background pipeline (like started with <code>command &amp;</code>) <code>0</code> zero The name of the shell or the shell script (filename). Set by the shell itself.If Bash is started with a filename to execute (script), it\\'s set to this filename. If started with the <code>-c &lt;CMDLINE&gt;</code> option (commandline given as argument), then <code>$0</code> will be the first argument after the given <code>&lt;CMDLINE&gt;</code>. Otherwise, it is set to the string given on invocation for <code>argv[0]</code>.Unlike popular belief, <code>$0</code> is not a positional parameter. <code>_</code> underscore A kind of catch-all parameter. Directly after shell invocation, it\\'s set to the filename used to invoke Bash, or the absolute or relative path to the script, just like <code>$0</code> would show it. Subsequently, expands to the last argument to the previous command. Placed into the environment when executing commands, and set to the full pathname of these commands. When checking mail, this parameter holds the name of the mail file currently being checked."},{"location":"syntax/shellvars/#shell-variables","title":"Shell Variables","text":""},{"location":"syntax/shellvars/#bash","title":"BASH","text":"Variable: <code>BASH</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>Expands to the full file name used to invoke the current instance of Bash.</p>"},{"location":"syntax/shellvars/#bashopts","title":"BASHOPTS","text":"Variable: <code>BASHOPTS</code> Since: 4.1-alpha Type: normal variable Read-only: yes Set by Bash: yes Default: n/a <p>A colon-separated list of enabled shell options.</p> <p>Each word in the list is a valid argument for the <code>-s</code> option to the shopt builtin command. The options appearing in <code>BASHOPTS</code> are those reported as on by <code>shopt</code>. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files.</p> <p>Example content:</p> <pre><code>cmdhist:expand_aliases:extquote:force_fignore:hostcomplete:interactive_comments:progcomp:promptvars:sourcepath\n</code></pre> <p>This variable is read-only.</p>"},{"location":"syntax/shellvars/#bashpid","title":"BASHPID","text":"Variable: <code>BASHPID</code> Since: 4.0-alpha Type: integer variable Read-only: yes Set by Bash: yes Default: n/a <p>Always expands to the process ID of the current Bash process. This differs from the special parameter <code>$</code> under certain circumstances, such as subshells that do not require Bash to be re-initialized.</p>"},{"location":"syntax/shellvars/#bash_aliases","title":"BASH_ALIASES","text":"Variable: <code>BASH_ALIASES</code> Since: unknown Type: associative array Read-only: no Set by Bash: yes Default: n/a <p>An associative array variable whose members correspond to the internal list of aliases as maintained by the alias builtin. Elements added to this array appear in the alias list; unsetting array elements cause aliases to be removed from the alias list.</p> <p>The associative key is the name of the alias as used with the <code>alias</code> builtin command.</p>"},{"location":"syntax/shellvars/#bash_argc","title":"BASH_ARGC","text":"Variable: <code>BASH_ARGC</code> Since: 3.0 Type: integer indexed array Read-only: no Set by Bash: only in extended debugging mode Default: n/a <p>An array variable whose values are the number of parameters in each frame of the current Bash execution call stack.</p> <p>The number of parameters to the current subroutine (shell function or script executed with <code>.</code> or <code>source</code> builtin command) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto <code>BASH_ARGC</code>.</p>"},{"location":"syntax/shellvars/#bash_argv","title":"BASH_ARGV","text":"Variable: <code>BASH_ARGV</code> Since: 3.0 Type: integer indexed array Read-only: no Set by Bash: only in extended debugging mode Default: n/a <p>An array variable containing all of the parameters in the current Bash execution call stack.</p> <p>The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto <code>BASH_ARGV</code>.</p>"},{"location":"syntax/shellvars/#bash_argv0","title":"BASH_ARGV0","text":"Variable: <code>BASH_ARGV0</code> Since: 5.0-alpha Type: string Read-only: no Set by Bash: yes Default: same as <code>$0</code> <p>Expands to the name of the shell or shell script - as the special parameter <code>$0</code> does. Assignments to <code>BASH_ARGV0</code> causes the value to be assigned to <code>$0</code>.</p> <p>If this parameter is unset, it loses its special properties, even if subsequently reset.</p>"},{"location":"syntax/shellvars/#bash_cmds","title":"BASH_CMDS","text":"Variable: <code>BASH_CMDS</code> Since: unknown Type: associative array Read-only: no Set by Bash: yes Default: n/a <p>An associative array variable whose members correspond to the internal hash table of commands as maintained by the <code>hash</code> builtin command. Elements added to this array appear in the hash table; unsetting array elements cause commands to be removed from the hash table.</p> <p>The associative key is the name of the command as used with the <code>hash</code> builtin command.</p>"},{"location":"syntax/shellvars/#bash_command","title":"BASH_COMMAND","text":"Variable: <code>BASH_COMMAND</code> Since: 3.0 Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap.</p>"},{"location":"syntax/shellvars/#bash_compat","title":"BASH_COMPAT","text":"Variable: <code>BASH_COMPAT</code> Since: 4.3-alpha Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>The value is used to set the shell's compatibility level. The value may be a decimal number (e.g., <code>4.2</code>) or an integer (e.g., <code>42</code>) corresponding to the desired compatibility level. If <code>BASH_COMPAT</code> is unset or set to the empty string, the compatibility level is set to the default for the current version. If <code>BASH_COMPAT</code> is set to a value that is not one of the valid compatibility levels, the shell prints an error message and sets the compatibility level to the default for the current version. The valid compatibility levels correspond to the compatibility options accepted by the shopt builtin. The current version is also a valid value.</p>"},{"location":"syntax/shellvars/#bash_execution_string","title":"BASH_EXECUTION_STRING","text":"Variable: <code>BASH_EXECUTION_STRING</code> Since: 3.0 Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>The command argument to the <code>-c</code> invocation option.</p>"},{"location":"syntax/shellvars/#bash_lineno","title":"BASH_LINENO","text":"Variable: <code>BASH_LINENO</code> Since: 3.0 Type: integer indexed array Read-only: no Set by Bash: yes Default: n/a <p>An array variable whose members are the line numbers in source files corresponding to each member of <code>FUNCNAME</code>.</p> <p><code>${BASH_LINENO[$i]}</code> is the line number in the source file where <code>${FUNCNAME[$ifP]}</code> was called. The corresponding source file name is <code>${BASH_SOURCE[$i]}</code>. Use <code>LINENO</code> to obtain the current line number.</p>"},{"location":"syntax/shellvars/#bash_rematch","title":"BASH_REMATCH","text":"Variable: <code>BASH_REMATCH</code> Since: 3.0 Type: integer indexed array Read-only: no Set by Bash: yes Default: n/a <p>An array variable whose members are assigned by the <code>=~</code> binary operator to the <code>[[</code> conditional command.</p> <p>The element with index 0 is the portion of the string matching the entire regular expression. The element with index <code>n</code> is the portion of the string matching the nth parenthesized subexpression.</p> <p>Before Bash version 5.1-alpha this variable was readonly.</p>"},{"location":"syntax/shellvars/#bash_source","title":"BASH_SOURCE","text":"Variable: <code>BASH_SOURCE</code> Since: 3.0 Type: integer indexed array Read-only: no Set by Bash: yes Default: n/a <p>An array variable whose members are the source filenames corresponding to the elements in the <code>FUNCNAME</code> array variable.</p>"},{"location":"syntax/shellvars/#bash_subshell","title":"BASH_SUBSHELL","text":"Variable: <code>BASH_SUBSHELL</code> Since: 3.0 Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>Incremented by one each time a subshell or subshell environment is spawned. The initial value is 0.</p>"},{"location":"syntax/shellvars/#bash_versinfo","title":"BASH_VERSINFO","text":"Variable: <code>BASH_VERSINFO</code> Since: 2.0 Type: integer indexed array Read-only: yes Set by Bash: yes Default: n/a <p>A readonly array variable whose members hold version information for this instance of Bash. The values assigned to the array members are as follows:</p> -- -- BASH_VERSINFO[0] The major version number (the release) BASH_VERSINFO[1] The minor version number (the version) BASH_VERSINFO[2] The patch level BASH_VERSINFO[3] The build version BASH_VERSINFO[4] The release status (e.g., beta1) BASH_VERSINFO[5] The value of <code>MACHTYPE</code>"},{"location":"syntax/shellvars/#bash_version","title":"BASH_VERSION","text":"Variable: <code>BASH_VERSION</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>Expands to a string describing the version of this instance of Bash.</p> <p>Since Bash 2.0 it includes the shell's \"release status\" (alpha[N], beta[N], release).</p>"},{"location":"syntax/shellvars/#child_max","title":"CHILD_MAX","text":"Variable: <code>CHILD_MAX</code> Since: 4.3-alpha Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>Set the number of exited child status values for the shell to remember. Bash will not allow this value to be decreased below a POSIX-mandated minimum, and there is a maximum value (currently 8192) that this may not exceed. The minimum value is system-dependent.</p>"},{"location":"syntax/shellvars/#comp_cword","title":"COMP_CWORD","text":"Variable: <code>COMP_CWORD</code> Since: unknown Type: normal variable Read-only: no Set by Bash: only for programmable completion facilities Default: n/a <p>An index into <code>COMP_WORDS</code> of the word containing the current cursor position.</p>"},{"location":"syntax/shellvars/#comp_key","title":"COMP_KEY","text":"Variable: <code>COMP_KEY</code> Since: unknown Type: normal variable Read-only: no Set by Bash: only for programmable completion facilities Default: n/a <p>The key (or final key of a key sequence) used to invoke the current completion function.</p>"},{"location":"syntax/shellvars/#comp_line","title":"COMP_LINE","text":"Variable: <code>COMP_LINE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: only for programmable completion facilities Default: n/a <p>The current command line.</p>"},{"location":"syntax/shellvars/#comp_point","title":"COMP_POINT","text":"Variable: <code>COMP_POINT</code> Since: unknown Type: normal variable Read-only: no Set by Bash: only for programmable completion facilities Default: n/a <p>The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to <code>${#COMP_LINE}</code>.</p>"},{"location":"syntax/shellvars/#comp_type","title":"COMP_TYPE","text":"Variable: <code>COMP_TYPET</code> Since: unknown Type: normal variable Read-only: no Set by Bash: only for programmable completion facilities Default: n/a <p>Set to an integer value corresponding to the type of completion attempted that caused a completion function to be called:</p> -- -- <code>TAB</code> normal completion <code>?</code> listing completions after successive tabs <code>!</code> listing alternatives on partial word completion <code>@</code> to list completions if the word is not unmodified <code>%</code> for menu completion <p>FIXME</p> <p>where are the integer values?</p>"},{"location":"syntax/shellvars/#comp_wordbreaks","title":"COMP_WORDBREAKS","text":"Variable: <code>COMP_WORDBREAKS</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>Reports the set of characters that the readline library treats as word separators when performing word completion.</p> <p>If this parameter is unset, it loses its special properties, even if it is subsequently reset.</p>"},{"location":"syntax/shellvars/#comp_words","title":"COMP_WORDS","text":"Variable: <code>COMP_WORDS</code> Since: unknown Type: integer indexed array Read-only: no Set by Bash: only for programmable completion facilities Default: n/a <p>An array variable consisting of the individual words in the current command line. The line is split into words as readline would split it, using <code>COMP_WORDBREAKS</code> as described above.</p>"},{"location":"syntax/shellvars/#coproc","title":"COPROC","text":"Variable: <code>COPROC</code> Since: unknown Type: integer indexed array Read-only: no Set by Bash: yes Default: n/a <p>An array variable created to hold the file descriptors for output from and input to an unnamed coprocess.</p>"},{"location":"syntax/shellvars/#dirstack","title":"DIRSTACK","text":"Variable: <code>DIRSTACK</code> Since: unknown Type: integer indexed array Read-only: no Set by Bash: yes Default: n/a <p>An array variable containing the current contents of the directory stack.</p> <p>Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories.</p> <p>Assignment to this variable will not change the current directory.</p> <p>If this parameter is unset, it loses its special properties, even if it is subsequently reset.</p>"},{"location":"syntax/shellvars/#epochrealtime","title":"EPOCHREALTIME","text":"Variable: <code>EPOCHREALTIME</code> Since: 5.0-alpha Type: integer variable Read-only: no Set by Bash: yes Default: n/a <p>Expands to the number of seconds since Unix expoch as a floating point value with micro-second granularity.</p> <p>Assignments to this parameter are ignored. If this parameter is unset, it loses its special properties, even if it is subsequently reset.</p>"},{"location":"syntax/shellvars/#epochseconds","title":"EPOCHSECONDS","text":"Variable: <code>EPOCHSECONDS</code> Since: 5.0-alpha Type: integer variable Read-only: no Set by Bash: yes Default: n/a <p>Expands to the number of seconds since Unix expoch.</p> <p>Assignments to this parameter are ignored. If this parameter is unset, it loses its special properties, even if it is subsequently reset.</p>"},{"location":"syntax/shellvars/#euid","title":"EUID","text":"Variable: <code>EUID</code> Since: unknown Type: integer variable Read-only: yes Set by Bash: yes Default: n/a <p>Expands to the effective user ID of the current user, initialized at shell startup.</p> <p>!</p> <p>Do not rely on this variable when security is a concern.</p>"},{"location":"syntax/shellvars/#funcname","title":"FUNCNAME","text":"Variable: <code>FUNCNAME</code> Since: 2.04 Type: integer indexed array Read-only: no Set by Bash: only inside shell functions Default: n/a <p>An array variable containing the names of all shell functions currently in the execution call stack.</p> <p>The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is \"main\".</p> <p>This variable can be used with <code>BASH_LINENO</code> and <code>BASH_SOURCE</code>: Each element of <code>FUNCNAME</code> has corresponding elements in <code>BASH_LINENO</code> and <code>BASH_SOURCE</code> to describe the call stack. For instance, <code>${FUNCNAME[$i]}</code> was called from the file <code>${BASH_SOURCE[$i+1]}</code> at line number <code>${BASH_LINENO[$i]}</code>. The caller builtin command displays the current call stack using this information.</p> <p>This variable exists only when a shell function is executing.</p> <p>Assignments to this parameter have no effect and return an error status.</p> <p>If this parameter is unset, it loses its special properties, even if it is subsequently reset.</p>"},{"location":"syntax/shellvars/#groups","title":"GROUPS","text":"Variable: <code>GROUPS</code> Since: 2.01 Type: integer indexed array Read-only: no Set by Bash: yes Default: n/a <p>An array variable containing the list of groups of which the current user is a member.</p> <p>Assignments to this parameter have no effect and return an error status.</p> <p>If this parameter is unset, it loses its special properties, even if it is subsequently reset.</p>"},{"location":"syntax/shellvars/#histcmd","title":"HISTCMD","text":"Variable: <code>HISTCMD</code> Since: 1.14.0 Type: integer variable Read-only: no Set by Bash: yes Default: n/a <p>Expands to the history number (index in the history list) of the current command.</p> <p>If this parameter is unset, it loses its special properties, even if it is subsequently reset.</p>"},{"location":"syntax/shellvars/#hostname","title":"HOSTNAME","text":"Variable: <code>HOSTNAME</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>Automatically set to the name of the current host.</p>"},{"location":"syntax/shellvars/#hosttype","title":"HOSTTYPE","text":"Variable: <code>HOSTTYPE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: system-dependent <p>Automatically set to a string that uniquely describes the type of machine on which Bash is executing.</p> <p>Example content:</p> <pre><code>x86_64\n</code></pre>"},{"location":"syntax/shellvars/#lineno","title":"LINENO","text":"Variable: <code>LINENO</code> Since: unknown Type: integer variable Read-only: no Set by Bash: yes Default: n/a <p>Each time this parameter is referenced, the shell substitutes a decimal number representing the current sequential line number (starting with 1) within a script or function.</p> <p>When not in a script or function, the value substituted is not guaranteed to be meaningful.</p> <p>If this parameter is unset, it loses its special properties, even if it is subsequently reset.</p>"},{"location":"syntax/shellvars/#machtype","title":"MACHTYPE","text":"Variable: <code>MACHTYPE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: system-dependent <p>Automatically set to a string that fully describes the system type on which Bash is executing, in the standard GNU \"cpu-company-system\" format.</p> <p>Example content:</p> <pre><code>x86_64-unknown-linux-gnu\n</code></pre>"},{"location":"syntax/shellvars/#mapfile","title":"MAPFILE","text":"Variable: <code>MAPFILE</code> Since: unknown Type: integer indexed array Read-only: no Set by Bash: yes Default: n/a <p>An array variable created to hold the text read by the mapfile builtin command when no variable name is supplied.</p>"},{"location":"syntax/shellvars/#oldpwd","title":"OLDPWD","text":"Variable: <code>OLDPWD</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>The previous working directory as set by the cd command.</p>"},{"location":"syntax/shellvars/#optarg","title":"OPTARG","text":"Variable: <code>OPTARG</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>The value of the last option argument processed by the <code>getopts</code> builtin command.</p>"},{"location":"syntax/shellvars/#optind","title":"OPTIND","text":"Variable: <code>OPTIND</code> Since: unknown Type: integer variable Read-only: no Set by Bash: yes Default: n/a <p>The index of the next argument to be processed by the <code>getopts</code> builtin command.</p>"},{"location":"syntax/shellvars/#ostype","title":"OSTYPE","text":"Variable: <code>OSTYPE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: system-dependent <p>Automatically set to a string that describes the operating system on which Bash is executing.</p> <p>Example content:</p> <pre><code>linux-gnu\n</code></pre>"},{"location":"syntax/shellvars/#pipestatus","title":"PIPESTATUS","text":"Variable: <code>PIPESTATUS</code> Since: 2.0 Type: integer indexed array Read-only: no Set by Bash: yes Default: n/a <p>An array variable containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).</p>"},{"location":"syntax/shellvars/#ppid","title":"PPID","text":"Variable: <code>PPID</code> Since: unknown Type: integer variable Read-only: yes Set by Bash: yes Default: n/a <p>The process ID of the shell's parent process.</p>"},{"location":"syntax/shellvars/#pwd","title":"PWD","text":"Variable: <code>PWD</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>The current working directory as set by the cd builtin command.</p>"},{"location":"syntax/shellvars/#random","title":"RANDOM","text":"Variable: <code>RANDOM</code> Since: unknown Type: integer variable Read-only: no Set by Bash: yes Default: n/a <p>Each time this parameter is referenced, a random integer between 0 and 32767 is generated. The sequence of random numbers may be initialized by assigning a value to <code>RANDOM</code>.</p> <p>If this parameter is unset, it loses its special properties, even if it is subsequently reset.</p>"},{"location":"syntax/shellvars/#readline_line","title":"READLINE_LINE","text":"Variable: <code>READLINE_LINE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>The contents of the readline line buffer, for use with <code>bind -x</code>.</p>"},{"location":"syntax/shellvars/#readline_point","title":"READLINE_POINT","text":"Variable: <code>READLINE_POINT</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>The position of the insertion point in the readline line buffer, for use with <code>bind -x</code>.</p>"},{"location":"syntax/shellvars/#reply","title":"REPLY","text":"Variable: <code>REPLY</code> Since: unknown Type: normal variable Read-only: no Set by Bash: only by the read builtin command Default: n/a <p>Set to the line of input read by the read builtin command when no arguments are supplied that name target variables.</p>"},{"location":"syntax/shellvars/#seconds","title":"SECONDS","text":"Variable: <code>SECONDS</code> Since: unknown Type: integer variable Read-only: no Set by Bash: yes Default: n/a <p>Each time this parameter is referenced, the number of seconds since shell invocation is returned. If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned.</p> <p>If this parameter is unset, it loses its special properties, even if it is subsequently reset.</p>"},{"location":"syntax/shellvars/#shellopts","title":"SHELLOPTS","text":"Variable: <code>SHELLOPTS</code> Since: unknown Type: normal variable Read-only: yes Set by Bash: yes Default: n/a <p>A colon-separated list of enabled shell options. Each word in the list is a valid argument for the <code>-o</code> option to the set builtin command. The options appearing in <code>SHELLOPTS</code> are those reported as on by <code>set -o</code>.</p> <p>If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files.</p>"},{"location":"syntax/shellvars/#shlvl","title":"SHLVL","text":"Variable: <code>SHLVL</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>Incremented by one each time an instance of Bash is started.</p>"},{"location":"syntax/shellvars/#uid","title":"UID","text":"Variable: <code>UID</code> Since: unknown Type: integer variable Read-only: yes Set by Bash: yes Default: n/a <p>Expands to the user ID of the current user, initialized at shell startup.</p> <p>:!: Do not rely on this variable when security is a concern.</p>"},{"location":"syntax/shellvars/#bash_env","title":"BASH_ENV","text":"Variable: <code>BASH_ENV</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>If this parameter is set when Bash is executing a shell script, its value is interpreted as a filename containing commands to initialize the shell, as in <code>~/.bashrc</code>. The value of <code>BASH_ENV</code> is subjected to</p> <ul> <li>parameter expansion</li> <li>command substitution</li> <li>arithmetic expansion</li> </ul> <p>before being interpreted as a file name.</p> <p><code>PATH</code> is not used to search for the resultant file name.</p>"},{"location":"syntax/shellvars/#bash_xtracefd","title":"BASH_XTRACEFD","text":"Variable: <code>BASH_XTRACEFD</code> Since: 4.1-alpha Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>If set to an integer corresponding to a valid file descriptor, Bash will write the trace output generated when <code>set -x</code> is enabled to that file descriptor.</p> <p>The file descriptor is closed when <code>BASH_XTRACEFD</code> is unset or assigned a new value.</p> <p>Unsetting <code>BASH_XTRACEFD</code> or assigning it the empty string causes the trace output to be sent to the standard error. Note that setting <code>BASH_XTRACEFD</code> to 2 (the standard error file descriptor) and then unsetting it will result in the standard error being closed.</p>"},{"location":"syntax/shellvars/#cdpath","title":"CDPATH","text":"Variable: <code>CDPATH</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>The search path for the cd builtin command.</p> <p>This is a colon-separated list of directories in which the shell looks for destination directories specified by the <code>cd</code> command.</p> <p>Example content:</p> <pre><code>.:~:/usr\n</code></pre>"},{"location":"syntax/shellvars/#columns","title":"COLUMNS","text":"Variable: <code>COLUMNS</code> Since: unknown Type: normal variable Read-only: no Set by Bash: on <code>|SIGWINCH</code> Default: n/a <p>Used by the select compound command to determine the terminal width when printing selection lists. Automatically set upon receipt of a <code>SIGWINCH</code>.</p>"},{"location":"syntax/shellvars/#compreply","title":"COMPREPLY","text":"Variable: <code>COMPREPLY</code> Since: unknown Type: integer indexed array Read-only: no Set by Bash: no Default: n/a <p>An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility.</p>"},{"location":"syntax/shellvars/#emacs","title":"EMACS","text":"Variable: <code>EMACS</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>If Bash finds this variable in the environment when the shell starts with value \"t\", it assumes that the shell is running in an Emacs shell buffer and disables line editing.</p>"},{"location":"syntax/shellvars/#env","title":"ENV","text":"Variable: <code>ENV</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>Similar to <code>BASH_ENV</code>: Used when the shell is invoked in POSIX\u00ae mode.</p>"},{"location":"syntax/shellvars/#fcedit","title":"FCEDIT","text":"Variable: <code>FCEDIT</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>The default editor for the <code>fc</code> builtin command.</p>"},{"location":"syntax/shellvars/#fignore","title":"FIGNORE","text":"Variable: <code>FIGNORE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>A colon-separated list of suffixes to ignore when performing filename completion. A filename whose suffix matches one of the entries in <code>FIGNORE</code> is excluded from the list of matched filenames.</p> <p>Example content:</p> <pre><code>.o:~\n</code></pre>"},{"location":"syntax/shellvars/#funcnest","title":"FUNCNEST","text":"Variable: <code>FUNCNEST</code> Since: 4.2-alpha Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>If set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed this nesting level will cause the current command to abort.</p> <p>Negative values, 0 or non-numeric assignments have the effect as if <code>FUNCNEST</code> was unset or empty: No nest control</p>"},{"location":"syntax/shellvars/#globignore","title":"GLOBIGNORE","text":"Variable: <code>GLOBIGNORE</code> Since: 2.0 Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>A colon-separated list of patterns defining the set of filenames to be ignored by pathname expansion. If a filename matched by a pathname expansion pattern also matches one of the patterns in <code>GLOBIGNORE</code>, it is removed from the list of matches.</p>"},{"location":"syntax/shellvars/#histcontrol","title":"HISTCONTROL","text":"Variable: <code>HISTCONTROL</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>A colon-separated list of values controlling how commands are saved on the history list:</p> <code>ignorespace</code> lines which begin with a space character are not saved in the history list <code>ignoredups</code> don't save lines matching the previous history entry <code>ignoreboth</code> short for <code>ignorespace:ignoredups</code> <code>erasedups</code> remove all previous lines matching the current line from the history list before the current line is saved <p>Any value not in the above list is ignored.</p> <p>If <code>HISTCONTROL</code> is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of <code>HISTIGNORE</code>. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of <code>HISTCONTROL</code>.</p>"},{"location":"syntax/shellvars/#histfile","title":"HISTFILE","text":"Variable: <code>HISTFILE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: if unset Default: \\'\\' \\~/.bash_history\\'\\' <p>The |name of the file in which command history is saved.|</p> <p>If unset, the command history is not saved when an interactive shell exits.</p>"},{"location":"syntax/shellvars/#histfilesize","title":"HISTFILESIZE","text":"Variable: <code>HISTFILESIZE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: if unset Default: <code>HISTSIZE</code> <p>The |maximum number of lines contained in the history file.|</p> <p>When this variable is assigned a value, the history file is truncated, if necessary, by removing the oldest entries, to contain no more than the given number of lines. If the given number of lines is 0 (zero), the file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation.</p> <p>The history file is also truncated to this size after writing it when an interactive shell exits.</p>"},{"location":"syntax/shellvars/#histignore","title":"HISTIGNORE","text":"Variable: <code>HISTIGNORE</code> Since: 2.0 Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit '<code>*</code>' is appended).</p> <p>Each pattern is tested against the line after the checks specified by <code>HISTCONTROL</code> are applied.</p> <p>In addition to the normal shell pattern matching characters, \"&amp;\" matches the previous history line. \"&amp;\" may be escaped using a backslash; the backslash is removed before attempting a match.</p> <p>The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of <code>HISTIGNORE</code>.</p>"},{"location":"syntax/shellvars/#histsize","title":"HISTSIZE","text":"Variable: <code>HISTSIZE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: if unset Default: set at compile time (default 500) <p>The number of commands to remember in the command history.</p> <p>If the number is set to 0 (zero), then the history list is disabled. If the number is set to any negative number, then the history list is unlimited.</p>"},{"location":"syntax/shellvars/#histtimeformat","title":"HISTTIMEFORMAT","text":"Variable: <code>HISTTIMEFORMAT</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>If this variable is set and not null, its value is used as a format string for <code>strftime(3)</code> to print the time stamp associated with each history entry displayed by the history builtin.</p> <p>If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines.</p>"},{"location":"syntax/shellvars/#home","title":"HOME","text":"Variable: <code>HOME</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>The home directory of the current user.</p> <p>The default argument for the cd builtin command.</p> <p>The value of this variable is also used when performing tilde expansion.</p>"},{"location":"syntax/shellvars/#hostfile","title":"HOSTFILE","text":"Variable: <code>HOSTFILE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>Contains the name of a file in the same format as <code>/etc/hosts</code> that should be read when the shell needs to complete a hostname.</p> <p>The list of possible hostname completions may be changed while the shell is running. the next time hostname completion is attempted after the value is changed, Bash adds the contents of the new file to the existing list.</p> <p>If <code>HOSTFILE</code> is set, but has no value, or does not name a readable file, Bash attempts to read <code>/etc/hosts</code> to obtain the list of possible hostname completions.</p> <p>When <code>HOSTFILE</code> is unset, the hostname list is cleared.</p>"},{"location":"syntax/shellvars/#ifs","title":"IFS","text":"Variable: <code>IFS</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: <code>&lt;space&gt;&lt;tab&gt;&lt;newline&gt;</code> <p>The Internal Field Separator |that is used for word splitting after| expansion and to split lines into words with the read builtin command.</p>"},{"location":"syntax/shellvars/#ignoreeof","title":"IGNOREEOF","text":"Variable: <code>IGNOREEOF</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: 10 (when invalid) <p>Controls the action of an interactive shell on receipt of an <code>EOF</code> character (e.g. by Ctrl-D) as the sole input.</p> <p>If set, the value is the number of consecutive EOF characters which must be typed as the first characters on an input line before Bash exits.</p> <p>If the variable exists but does not have a numeric value, or has no value, the default value is 10.</p> <p>If it does not exist, <code>EOF</code> signifies the end of input to the shell.</p>"},{"location":"syntax/shellvars/#inputrc","title":"INPUTRC","text":"Variable: <code>INPUTRC</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>The filename for the readline startup file, overriding the default of <code>~/.inputrc</code>.</p>"},{"location":"syntax/shellvars/#lang","title":"LANG","text":"Variable: <code>LANG</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>Used to determine the locale category for any category not specifically selected with a variable starting with <code>LC_</code>.</p>"},{"location":"syntax/shellvars/#lc_all","title":"LC_ALL","text":"Variable: <code>LC_ALL</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>This variable overrides the value of <code>LANG</code> and any other <code>LC_</code> variable specifying a locale category.</p>"},{"location":"syntax/shellvars/#lc_collate","title":"LC_COLLATE","text":"Variable: <code>LC_COLLATE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>This variable determines the collation order used when sorting the results of pathname expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within pathname expansion and pattern matching.</p>"},{"location":"syntax/shellvars/#lc_ctype","title":"LC_CTYPE","text":"Variable: <code>LC_CTYPE</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>This variable determines the interpretation of characters and the behavior of character classes within pathname expansion and pattern matching.</p>"},{"location":"syntax/shellvars/#lc_messages","title":"LC_MESSAGES","text":"Variable: <code>LC_MESSAGES</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>This variable determines the locale used to translate double- quoted strings preceded by a <code>$</code>.</p>"},{"location":"syntax/shellvars/#lc_numeric","title":"LC_NUMERIC","text":"Variable: <code>LC_NUMERIC</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>This variable determines the locale category used for number formatting.</p>"},{"location":"syntax/shellvars/#lines","title":"LINES","text":"Variable: <code>LINES</code> Since: unknown Type: normal variable Read-only: no Set by Bash: on <code>|SIGWINCH</code> Default: n/a <p>Used by the select compound command to determine the column length for printing selection lists. Automatically set upon receipt of a <code>SIGWINCH</code>.</p>"},{"location":"syntax/shellvars/#mail","title":"MAIL","text":"Variable: <code>MAIL</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: system-dependent <p>If this parameter is set to a file or directory name and the <code>MAILPATH</code> variable is not set, Bash informs the user of the arrival of mail in the specified file or Maildir-format direc\u2010 tory.</p>"},{"location":"syntax/shellvars/#mailcheck","title":"MAILCHECK","text":"Variable: <code>MAILCHECK</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: 60 <p>Specifies |how often (in seconds) Bash checks for mail.|</p> <p>When it is time to check for mail, the shell does so before displaying the primary prompt.</p> <p>If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking.</p>"},{"location":"syntax/shellvars/#mailpath","title":"MAILPATH","text":"Variable: <code>MAILPATH</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: system-dependent <p>A colon-separated list of file names to be checked for mail.</p> <p>The message to be printed when mail arrives in a particular file may be specified by separating the file name from the message with a '?' (question mark).</p> <p>When used in the text of the message, <code>$_</code> expands to the name of the current mailfile.</p> <p>Example content:</p> <pre><code>/var/mail/bfox?\"You have mail\":~/shell-mail?\"$_ has mail!\"\n</code></pre>"},{"location":"syntax/shellvars/#opterr","title":"OPTERR","text":"Variable: <code>OPTERR</code> Since: unknown Type: normal variable Read-only: no Set by Bash: yes Default: 1 (set on startup) <p>If set to the value 1, Bash displays error messages generated by the <code>getopts</code> builtin command.</p> <p><code>OPTERR</code> is initialized to 1 each time the shell is invoked or a shell script is executed.</p>"},{"location":"syntax/shellvars/#path","title":"PATH","text":"Variable: <code>PATH</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: system-dependent (set on compile time) <p>The search path for commands. This is a colon-separated list of directories in which the shell looks for commands.</p> <p>A zero-length (null) directory name in the value of <code>PATH</code> indicates the current directory.</p> <p>A null directory name may appear as two adjacent colons, or as an initial or trailing colon.</p> <p>There can be a static path compiled in for use in a restricted shell.</p>"},{"location":"syntax/shellvars/#posixly_correct","title":"POSIXLY_CORRECT","text":"Variable: <code>POSIXLY_CORRECT</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>If this variable is in the environment when Bash starts, the shell enters posix mode before reading the startup files, as if the <code>--posix</code> invocation option had been supplied.</p> <p>If it is set while the shell is running, Bash enables posix mode, as if the command <code>set -o posix</code> had been executed.</p>"},{"location":"syntax/shellvars/#prompt_command","title":"PROMPT_COMMAND","text":"Variable: <code>PROMPT_COMMAND</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>If set, the value is executed as a command prior to issuing each primary prompt.</p>"},{"location":"syntax/shellvars/#prompt_commands","title":"PROMPT_COMMANDS","text":"Variable: <code>PROMPT_COMMANDS</code> Since: 5.1-alpha Type: integer indexed array Read-only: no Set by Bash: no Default: n/a <p>If set, each element is executed as a command prior to issuing each primary prompt (like <code>PROMPT_COMMAND</code>, just as array).</p>"},{"location":"syntax/shellvars/#prompt_dirtrim","title":"PROMPT_DIRTRIM","text":"Variable: <code>PROMPT_DIRTRIM</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the <code>\\w</code> and <code>\\W</code> prompt string escapes.</p> <p>Characters removed are replaced with an ellipsis.</p>"},{"location":"syntax/shellvars/#ps0","title":"PS0","text":"Variable: <code>PS0</code> Since: 4.4.0 Type: normal variable Read-only: no Set by Bash: if unset Default: \\\"\\'\\'\\'\\'\\\" <p>Expanded |and displayed by interactive shells after reading a complete| command but before executing it.</p>"},{"location":"syntax/shellvars/#ps1","title":"PS1","text":"Variable: <code>PS1</code> Since: unknown Type: normal variable Read-only: no Set by Bash: if unset Default: \\\"\\'\\'\\s-\\v\\\\$ \\'\\'\\\" <p>The |value of this parameter is expanded and used as the primary prompt| string. See Controlling the Prompt.</p>"},{"location":"syntax/shellvars/#ps2","title":"PS2","text":"Variable: <code>PS2</code> Since: unknown Type: normal variable Read-only: no Set by Bash: if unset Default: \\\"\\'\\'&gt; \\'\\'\\\" <p>The |value of this parameter is expanded as with PS1 and used as the| secondary prompt string.</p>"},{"location":"syntax/shellvars/#ps3","title":"PS3","text":"Variable: <code>PS3</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>The value of this parameter is used as the prompt for the select command.</p>"},{"location":"syntax/shellvars/#ps4","title":"PS4","text":"Variable: <code>PS4</code> Since: unknown Type: normal variable Read-only: no Set by Bash: if unset Default: \\\"\\'\\'+ \\'\\'\\\" <p>The |value of this parameter is expanded as with <code>PS1</code> and the value is| printed before each command Bash displays during an execution trace. The first character of <code>PS4</code> is replicated multiple times, as necessary, to indicate multiple levels of indirection.</p>"},{"location":"syntax/shellvars/#shell","title":"SHELL","text":"Variable: <code>SHELL</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>The full pathname to the shell is kept in this environment variable. If it is not set when the shell starts, Bash assigns the full pathname of the current user's login shell.</p>"},{"location":"syntax/shellvars/#srandom","title":"SRANDOM","text":"Variable: <code>SRANDOM</code> Since: 5.1-alpha Type: normal variable Read-only: no Set by Bash: yes Default: n/a <p>A variable that delivers a 32bit random number. The random number generation uses platform specific generators in the background and a builtin fallback generator.</p>"},{"location":"syntax/shellvars/#timeformat","title":"TIMEFORMAT","text":"Variable: <code>TIMEFORMAT</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed.</p> <p>The % character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows, the braces denote optional portions:</p> <code>%%</code> a literal <code>%</code> (percent sign) <code>%[p][l]R</code> elapsed time in seconds <code>%[p][l]U</code> number of CPU seconds spent in user mode <code>%[p][l]S</code> number of CPU seconds spent in system mode <code>%P</code> CPU percentage, computed as <code>(%U + %S) / %R</code> <p>The optional modifiers (p and l) are:</p> <code>p</code> A digit specifying the precision. A value of 0 causes no decimal point or fraction to be output. At most three digits after the decimal point are shown. If not specified, the value 3 is used. <code>l</code> A longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included. <p>If this variable is not set, Bash acts as if it had the value</p> <pre><code>$'\\nreal\\t%3lR\\nuser\\t%3lU\\nsys%3lS'\n</code></pre> <p>If the value is null, no timing information is displayed.</p> <p>A trailing newline is added when the format string is displayed.</p>"},{"location":"syntax/shellvars/#tmout","title":"TMOUT","text":"Variable: <code>TMOUT</code> Since: 2.05b Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>If set to a value greater than zero, <code>TMOUT</code> is treated as the default timeout for the read builtin command.</p> <p>The <code>select</code> command terminates if input does not arrive after <code>TMOUT</code> seconds when input is coming from a terminal.</p> <p>In an interactive shell, the value is interpreted as the number of seconds to wait for input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if input does not arrive.</p>"},{"location":"syntax/shellvars/#tmpdir","title":"TMPDIR","text":"Variable: <code>TMPDIR</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>If set, Bash uses its value as the name of a directory in which Bash creates temporary files for the shell's use.</p>"},{"location":"syntax/shellvars/#auto_resume","title":"auto_resume","text":"Variable: <code>auto_resume</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>This variable controls how the shell interacts with the user and job control. If this variable is set, single word simple commands without redirections are treated as candidates for resumption of an existing stopped job. There is no ambiguity allowed; if there is more than one job beginning with the string typed, the job most recently accessed is selected. The name of a stopped job, in this context, is the command line used to start it. If set to the value exact, the string supplied must match the name of a stopped job exactly; if set to substring, the string supplied needs to match a substring of the name of a stopped job. The substring value provides functionality analogous to the %? job identifier.</p> <p>If set to any other value, the supplied string must be a prefix of a stopped job's name; this provides functionality analogous to the <code>%string</code> job identifier.</p>"},{"location":"syntax/shellvars/#histchars","title":"histchars","text":"Variable: <code>histchars</code> Since: unknown Type: normal variable Read-only: no Set by Bash: no Default: n/a <p>The two or three characters which control history expansion and tokenization.</p> <p>The first character is the history expansion character, the character which signals the start of a history expansion, normally '!' (exlamation mark).</p> <p>The second character is the quick substitution character, which is used as shorthand for re-running the previous command entered, substi tuting one string for another in the command. The default is '^' (carret).</p> <p>The optional third character is the character which indicates that the remainder of the line is a comment when found as the first character of a word, normally '#' (hash mark). The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment.</p>"},{"location":"syntax/words/","title":"Words...","text":"<p>FIXME</p> <p>This article needs a review, it covers two topics (command line splitting and word splitting) and mixes both a bit too much. But in general, it's still usable to help understand this behaviour, it's \"wrong but not wrong\".</p> <p>One fundamental principle of Bash is to recognize words entered at the command prompt, or under other circumstances like variable-expansion.</p>","tags":["bash","shell","scripting","token","words","split","splitting","recognition"]},{"location":"syntax/words/#splitting-the-commandline","title":"Splitting the commandline","text":"<p>Bash scans the command line and splits it into words, usually to put the parameters you enter for a command into the right C-memory (the <code>argv</code> vector) to later correctly call the command. These words are recognized by splitting the command line at the special character position, Space or Tab (the manual defines them as blanks). For example, take the echo program. It displays all its parameters separated by a space. When you enter an echo command at the Bash prompt, Bash will look for those special characters, and use them to separate the parameters.</p> <p>You don't know what I'm talking about? I'm talking about this:</p> <pre><code>$ echo Hello little world\nHello little world\n</code></pre> <p>In other words, something you do (and Bash does) everyday. The characters where Bash splits the command line (SPACE, TAB i.e. blanks) are recognized as delimiters. There is no null argument generated when you have 2 or more blanks in the command line. A sequence of more blank characters is treated as a single blank. Here's an example:</p> <pre><code>$ echo Hello little world\nHello little world\n</code></pre> <p>Bash splits the command line at the blanks into words, then it calls echo with each word as an argument. In this example, echo is called with three arguments: \"<code>Hello</code>\", \"<code>little</code>\" and \"<code>world</code>\"!</p> <p>Does that mean we can't echo more than one Space? Of course not! Bash treats blanks as special characters, but there are two ways to tell Bash not to treat them special: Escaping and quoting.</p> <p>Escaping a character means, to take away its special meaning. Bash will use an escaped character as text, even if it's a special one. Escaping is done by preceeding the character with a backslash:</p> <pre><code>$ echo Hello\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ little \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ world\nHello little world\n</code></pre> <p>None of the escaped spaces will be used to perform word splitting. Thus, echo is called with one argument: \"<code>Hello little world</code>\".</p> <p>Bash has a mechanism to \"escape\" an entire string: Quoting. In the context of command-splitting, which this section is about, it doesn't matter which kind of quoting you use: weak quoting or strong quoting, both cause Bash to not treat spaces as special characters:</p> <pre><code>$ echo \"Hello little world\"\nHello little world\n\n$ echo 'Hello little world'\nHello little world\n</code></pre> <p>What is it all about now? Well, for example imagine a program that expects a filename as an argument, like cat. Filenames can have spaces in them:</p> <pre><code>$ ls -l\ntotal 4\n-rw-r--r-- 1 bonsai bonsai 5 Apr 18 18:16 test file\n\n$ cat test file\ncat: test: No such file or directory\ncat: file: No such file or directory\n\n$ cat test\\ file\nm00!\n\n$ cat \"test file\"\nm00!\n</code></pre> <p>If you enter that on the command line with Tab completion, that will take care of the spaces. But Bash also does another type of splitting.</p>","tags":["bash","shell","scripting","token","words","split","splitting","recognition"]},{"location":"syntax/words/#word-splitting","title":"Word splitting","text":"<p>For a more technical description, please read the article about word splitting!</p> <p>The first kind of splitting is done to parse the command line into separate tokens. This is what was described above, it's a pure command line parsing.</p> <p>After the command line has been split into words, Bash will perform expansion, if needed - variables that occur in the command line need to be expanded (substituted by their value), for example. This is where the second type of word splitting comes in - several expansions undergo word splitting (but others do not).</p> <p>Imagine you have a filename stored in a variable:</p> <pre><code>MYFILE=\"test file\"\n</code></pre> <p>When this variable is used, its occurance will be replaced by its content.</p> <pre><code>$ cat $MYFILE\ncat: test: No such file or directory\ncat: file: No such file or directory\n</code></pre> <p>Though this is another step where spaces make things difficult, quoting is used to work around the difficulty. Quotes also affect word splitting:</p> <pre><code>$ cat \"$MYFILE\"\nm00!\n</code></pre>","tags":["bash","shell","scripting","token","words","split","splitting","recognition"]},{"location":"syntax/words/#example","title":"Example","text":"<p>Let's follow an unquoted command through these steps, assuming that the variable is set:</p> <pre><code>MYFILE=\"THE FILE.TXT\"\n</code></pre> <p>and the first review is:</p> <pre><code>echo The file is named $MYFILE\n</code></pre> <p>The parser will scan for blanks and mark the relevant words (\"splitting the command line\"):</p> Initial command line splitting: Word 1 Word 2 Word 3 Word 4 Word 5 Word 6 <code>echo</code> <code>The</code> <code>file</code> <code>is</code> <code>named</code> <code>$MYFILE</code> <p>A parameter/variable expansion is part of that command line, Bash will perform the substitution, and the word splitting on the results:</p> Word splitting after substitution: Word 1 Word 2 Word 3 Word 4 Word 5 Word 6 Word 7 <code>echo</code> <code>The</code> <code>file</code> <code>is</code> <code>named</code> <code>THE</code> <code>FILE.TXT</code> <p>Now let's imagine we quoted <code>$MYFILE</code>, the command line now looks like:</p> <pre><code>echo The file is named \"$MYFILE\"\n</code></pre> Word splitting after substitution (quoted!): Word 1 Word 2 Word 3 Word 4 Word 5 Word 6 <code>echo</code> <code>The</code> <code>file</code> <code>is</code> <code>named</code> <code>THE FILE.TXT</code>","tags":["bash","shell","scripting","token","words","split","splitting","recognition"]},{"location":"syntax/words/#see-also","title":"See also","text":"<ul> <li>Internal: Quoting and character escaping</li> <li>Internal: Word splitting</li> <li>Internal: Introduction to expansions and substitutions</li> <li>External: Grymore: Shellquoting</li> </ul>","tags":["bash","shell","scripting","token","words","split","splitting","recognition"]},{"location":"syntax/ccmd/arithmetic_eval/","title":"Arithmetic evaluation (command)","text":""},{"location":"syntax/ccmd/arithmetic_eval/#synopsis","title":"Synopsis","text":"<pre><code>(( &lt;EXPRESSION&gt; ))\n</code></pre>"},{"location":"syntax/ccmd/arithmetic_eval/#description","title":"Description","text":"<p>This command evaluates the arithmetic expression <code>&lt;EXPRESSION&gt;</code>.</p> <p>If the expression evaluates to 0 then the exit code of the expression is set to 1 (<code>FALSE</code>). If the expression evaluates to something else than 0, then the exit code of the expression is set to 0 (<code>TRUE</code>). For this return code mapping, please see this section.</p> <p>The functionality basically is equivalent to what the <code>let</code> builtin command does. The arithmetic evaluation compound command should be preferred.</p>"},{"location":"syntax/ccmd/arithmetic_eval/#examples","title":"Examples","text":""},{"location":"syntax/ccmd/arithmetic_eval/#portability-considerations","title":"Portability considerations","text":""},{"location":"syntax/ccmd/arithmetic_eval/#see-also","title":"See also","text":"<ul> <li>Internal: arithmetic expressions</li> <li>Internal: arithmetic expansion</li> <li>Internal: The <code>let</code> builtin command</li> </ul>"},{"location":"syntax/ccmd/c_for/","title":"The C-style for-loop","text":""},{"location":"syntax/ccmd/c_for/#synopsis","title":"Synopsis","text":"<pre><code>for (( &lt;EXPR1&gt; ; &lt;EXPR2&gt; ; &lt;EXPR3&gt; )); do\n &lt;LIST&gt;\ndone\n\n# as a special case: without semicolon after ((...))\nfor (( &lt;EXPR1&gt; ; &lt;EXPR2&gt; ; &lt;EXPR3&gt; )) do\n &lt;LIST&gt;\ndone\n\n# alternative, historical and undocumented syntax\nfor (( &lt;EXPR1&gt; ; &lt;EXPR2&gt; ; &lt;EXPR3&gt; )) {\n &lt;LIST&gt;\n}\n</code></pre>"},{"location":"syntax/ccmd/c_for/#description","title":"Description","text":"<p>The C-style for-loop is a compound command derived from the equivalent ksh88 feature, which is in turn derived from the C \"for\" keyword. Its purpose is to provide a convenient way to evaluate arithmetic expressions in a loop, plus initialize any required arithmetic variables. It is one of the main \"loop with a counter\" mechanisms available in the language.</p> <p>The <code>((;;))</code> syntax at the top of the loop is not an ordinary arithmetic compound command, but is part of the C-style for-loop's own syntax. The three sections separated by semicolons are arithmetic expression contexts. Each time one of the sections is to be evaluated, the section is first processed for: brace, parameter, command, arithmetic, and process substitution/expansion as usual for arithmetic contexts. When the loop is entered for the first time, <code>&lt;EXPR1&gt;</code> is evaluated, then <code>&lt;EXPR2&gt;</code> is evaluated and checked. If <code>&lt;EXPR2&gt;</code> is true, then the loop body is executed. After the first and all subsequent iterations, <code>&lt;EXPR1&gt;</code> is skipped, <code>&lt;EXPR3&gt;</code> is evaluated, then <code>&lt;EXPR2&gt;</code> is evaluated and checked again. This process continues until <code>&lt;EXPR2&gt;</code> is false.</p> <ul> <li><code>&lt;EXPR1&gt;</code> is to initialize variables before the first run.</li> <li><code>&lt;EXPR2&gt;</code> is to check for a termination condition. This is always the last section to evaluate prior to leaving the loop.</li> <li><code>&lt;EXPR3&gt;</code> is to change conditions after every iteration. For example, incrementing a counter.</li> </ul> <p>:!: If one of these arithmetic expressions in the for-loop is empty, it behaves as if it would be 1 (TRUE in arithmetic context).</p> <p>:!: Like all loops (Both types of <code>for</code>-loop, <code>while</code> and <code>until</code>), this loop can be:</p> <ul> <li>Terminated (broken) by the <code>break</code> builtin, optionally as <code>break N</code> to break out of <code>N</code> levels of nested loops.</li> <li>Forced immediately to the next iteration using the <code>continue</code> builtin, optionally as the <code>continue N</code> analog to <code>break N</code>.</li> </ul> <p>The equivalent construct using a while loop and the arithmetic expression compound command would be structured as:</p> <pre><code>(( &lt;EXPR1&gt; ))\nwhile (( &lt;EXPR2&gt; )); do\n &lt;LIST&gt;\n (( &lt;EXPR3&gt; ))\ndone\n</code></pre> <p>The equivalent <code>while</code> construct isn't exactly the same, because both, the <code>for</code> and the <code>while</code> loop behave differently in case you use the <code>continue</code> command.</p>"},{"location":"syntax/ccmd/c_for/#alternate-syntax","title":"Alternate syntax","text":"<p>Bash, Ksh93, Mksh, and Zsh also provide an alternate syntax for the <code>for</code> loop - enclosing the loop body in <code>{...}</code> instead of <code>do ... done</code>:</p> <pre><code>for ((x=1; x&lt;=3; x++))\n{\n echo $x\n}\n</code></pre> <p>This syntax is not documented and shouldn't be used. I found the parser definitions for it in 1.x code, and in modern 4.x code. My guess is that it's there for compatibility reasons. Unlike the other aforementioned shells, Bash does not support the analogous syntax for case..esac.</p>"},{"location":"syntax/ccmd/c_for/#return-status","title":"Return status","text":"<p>The return status is that of the last command executed from <code>&lt;LIST&gt;</code>, or <code>FALSE</code> if any of the arithmetic expressions failed.</p>"},{"location":"syntax/ccmd/c_for/#alternatives-and-best-practice","title":"Alternatives and best practice","text":"TODO: Show some alternate usages involving functions and local variables for initialization."},{"location":"syntax/ccmd/c_for/#examples","title":"Examples","text":""},{"location":"syntax/ccmd/c_for/#simple-counter","title":"Simple counter","text":"<p>A simple counter, the loop iterates 101 times (\"0\" to \"100\" are 101 numbers -&gt; 101 runs!), and everytime the variable <code>x</code> is set to the current value.</p> <ul> <li>It initializes <code>x = 0</code></li> <li>Before every iteration it checks if <code>x \u2264 100</code></li> <li> <p>After every iteration it changes <code>x++</code></p> <p>for ((x = 0 ; x &lt;= 100 ; x++)); do echo \"Counter: $x\" done</p> </li> </ul>"},{"location":"syntax/ccmd/c_for/#stepping-counter","title":"Stepping counter","text":"<p>This is the very same counter (compare it to the simple counter example above), but the change that is made is a <code>x += 10</code>. That means, it will count from 0 to 100, but with a step of 10.</p> <pre><code>for ((x = 0 ; x &lt;= 100 ; x += 10)); do\n echo \"Counter: $x\"\ndone\n</code></pre>"},{"location":"syntax/ccmd/c_for/#bits-analyzer","title":"Bits analyzer","text":"<p>This example loops through the bit-values of a Byte, beginning from 128, ending at 1. If that bit is set in the <code>testbyte</code>, it prints \"<code>1</code>\", else \"<code>0</code>\" =&gt; it prints the binary representation of the <code>testbyte</code> value (8 bits).</p> <pre><code>#!/usr/bin/env bash\n# Example written for http://wiki.bash-hackers.org/syntax/ccmd/c_for#bits_analyzer\n# Based on TheBonsai's original.\n\nfunction toBin {\n typeset m=$1 n=2 x='x[(n*=2)&gt;m]'\n for ((x = x; n /= 2;)); do\n printf %d $(( m &amp; n &amp;&amp; 1))\n done\n}\n\nfunction main {\n [[ $1 == +([0-9]) ]] || return\n typeset result\n if (( $(ksh -c 'printf %..2d $1' _ \"$1\") == ( result = $(toBin \"$1\") ) )); then\n printf '%s is %s in base 2!\\n' \"$1\" \"$result\"\n else\n echo 'Oops, something went wrong with our calculation.' &gt;&amp;2\n exit 1\n fi\n}\n\nmain \"${1:-123}\"\n\n# vim: set fenc=utf-8 ff=unix ft=sh :\n\n&lt;div hide&gt;\n\ntestbyte=123\nfor (( n = 128 ; n &gt;= 1 ; n /= 2 )); do\n if (( testbyte &amp; n )); then\n printf %d 1\n else\n printf %s 0\n fi\ndone\necho\n\n&lt;/div&gt;\n</code></pre> <p>Why that one begins at 128 (highest value, on the left) and not 1 (lowest value, on the right)? It's easier to print from left to right...</p> <p>We arrive at 128 for <code>n</code> through the recursive arithmetic expression stored in <code>x</code>, which calculates the next-greatest power of 2 after <code>m</code>. To show that it works, we use ksh93 to double-check the answer, because it has a built-in feature for <code>printf</code> to print a representation of any number in an arbitrary base (up to 64). Very few languages have that ability built-in, even things like Python.</p>"},{"location":"syntax/ccmd/c_for/#up-down-up-down","title":"Up, down, up, down...","text":"<p>This counts up and down from <code>0</code> to <code>${1:-5}</code>, <code>${2:-4}</code> times, demonstrating more complicated arithmetic expressions with multiple variables.</p> <pre><code>for (( incr = 1, n=0, times = ${2:-4}, step = ${1:-5}; (n += incr) % step || (incr *= -1, --times);)); do\n printf '%*s\\n' \"$((n+1))\" \"$n\"\ndone\n</code></pre> <pre><code>~ \\$ bash &lt;(xclip -o) 1\n\n 2\n 3\n 4\n 5\n 4\n 3\n 2\n\n1 0 1\n\n 2\n 3\n 4\n 5\n 4\n 3\n 2\n\n1\n</code></pre>"},{"location":"syntax/ccmd/c_for/#portability-considerations","title":"Portability considerations","text":"<ul> <li>C-style for loops aren't POSIX. They are available in Bash, ksh93, and zsh. All 3 have essentially the same syntax and behavior.</li> <li>C-style for loops aren't available in mksh.</li> </ul>"},{"location":"syntax/ccmd/c_for/#bugs","title":"Bugs","text":"<ul> <li>Fixed in 4.3. ~~There appears to be a bug as of Bash 4.2p10 in which command lists can't be distinguished from the for loop's arithmetic argument delimiter (both semicolons), so command substitutions within the C-style for loop expression can't contain more than one command.~~</li> </ul>"},{"location":"syntax/ccmd/c_for/#see-also","title":"See also","text":"<ul> <li>Internal: Arithmetic expressions</li> <li>Internal: The classic for-loop</li> <li>Internal: The while-loop</li> </ul>"},{"location":"syntax/ccmd/case/","title":"The case statement","text":""},{"location":"syntax/ccmd/case/#synopsis","title":"Synopsis","text":"<pre><code>case &lt;WORD&gt; in\n [(] &lt;PATTERN1&gt; ) &lt;LIST1&gt; ;; # or ;&amp; or ;;&amp; in Bash 4\n [(] &lt;PATTERN2&gt; ) &lt;LIST2&gt; ;;\n [(] &lt;PATTERN3&gt; | &lt;PATTERN4&gt; ) &lt;LIST3-4&gt; ;;\n ...\n [(] &lt;PATTERNn&gt;) &lt;LISTn&gt; [;;]\nesac\n</code></pre>"},{"location":"syntax/ccmd/case/#description","title":"Description","text":"<p>The <code>case</code>-statement can execute commands based on a pattern matching decision. The word <code>&lt;WORD&gt;</code> is matched against every pattern <code>&lt;PATTERNn&gt;</code> and on a match, the associated list <code>&lt;LISTn&gt;</code> is executed. Every commandlist is terminated by <code>;;</code>. This rule is optional for the very last commandlist (i.e., you can omit the <code>;;</code> before the <code>esac</code>). Every <code>&lt;PATTERNn&gt;</code> is separated from it's associated <code>&lt;LISTn&gt;</code> by a <code>)</code>, and is optionally preceded by a <code>(</code>.</p> <p>Bash 4 introduces two new action terminators. The classic behavior using <code>;;</code> is to execute only the list associated with the first matching pattern, then break out of the <code>case</code> block. The <code>;&amp;</code> terminator causes <code>case</code> to also execute the next block without testing its pattern. The <code>;;&amp;</code> operator is like <code>;;</code>, except the case statement doesn't terminate after executing the associated list - Bash just continues testing the next pattern as though the previous pattern didn't match. Using these terminators, a <code>case</code> statement can be configured to test against all patterns, or to share code between blocks, for example.</p> <p>The word <code>&lt;WORD&gt;</code> is expanded using tilde, parameter and variable expansion; arithmetic, command and process substitution; and quote removal. No word splitting, brace, or pathname expansion is done, which means you can leave expansions unquoted without problems:</p> <pre><code>var=\"test word\"\n\ncase $var in\n ...\nesac\n</code></pre> <p>This is similar to the behavior of the conditional expression command (\"new test command\") (also no word splitting for expansions).</p> <p>Unlike the C-case-statement, only the matching list and nothing else is executed. If more patterns match the word, only the first match is taken. (Note the comment about Bash v4 changes above.)</p> <p>Multiple <code>|</code>-delimited patterns can be specified for a single block. This is a POSIX-compatable equivalent to the <code>@(pattern-list)</code> extglob construct.</p> <p>The <code>case</code> statement is one of the most difficult commands to indent clearly, and people frequently ask about the most \"correct\" style. Just do your best - there are many variations of indenting style for <code>case</code> and no real agreed-upon best practice.</p>"},{"location":"syntax/ccmd/case/#examples","title":"Examples","text":"<p>Another one of my stupid examples...</p> <pre><code>printf '%s ' 'Which fruit do you like most?'\nread -${BASH_VERSION+e}r fruit\n\ncase $fruit in\n apple)\n echo 'Mmmmh... I like those!'\n ;;\n banana)\n echo 'Hm, a bit awry, no?'\n ;;\n orange|tangerine)\n echo $'Eeeks! I don't like those!\\nGo away!'\n exit 1\n ;;\n *)\n echo \"Unknown fruit - sure it isn't toxic?\"\nesac\n</code></pre> <p>Here's a practical example showing a common pattern involving a <code>case</code> statement. If the first argument is one of a valid set of alternatives, then perform some sysfs operations under Linux to control a video card's power profile. Otherwise, show a usage synopsis, and print the current power profile and GPU temperature.</p> <pre><code># Set radeon power management\nfunction clk {\n typeset base=/sys/class/drm/card0/device\n [[ -r ${base}/hwmon/hwmon0/temp1_input &amp;&amp; -r ${base}/power_profile ]] || return 1\n\n case $1 in\n low|high|default)\n printf '%s\\n' \"temp: $(&lt;${base}/hwmon/hwmon0/temp1_input)C\" \"old profile: $(&lt;${base}/power_profile)\"\n echo \"$1\" &gt;${base}/power_profile\n echo \"new profile: $(&lt;${base}/power_profile)\"\n ;;\n *)\n echo \"Usage: $FUNCNAME [ low | high | default ]\"\n printf '%s\\n' \"temp: $(&lt;${base}/hwmon/hwmon0/temp1_input)C\" \"current profile: $(&lt;${base}/power_profile)\"\n esac\n}\n</code></pre> <p>A template for experiments with <code>case</code> logic, showing shared code between blocks using <code>;&amp;</code>, and the non-short-circuiting <code>;;&amp;</code> operator:</p> <pre><code>#!/usr/bin/env bash\n\nf() {\n local -a \"$@\"\n local x\n\n for x; do\n case $x in\n $1)\n local \"$x\"'+=(1)' ;;&amp;\n $2)\n local \"$x\"'+=(2)' ;&amp;\n $3)\n local \"$x\"'+=(3)' ;;\n $1|$2)\n local \"$x\"'+=(4)'\n esac\n IFS=, local -a \"$x\"'=(\"${x}: ${'\"$x\"'[*]}\")'\n done\n\n for x; do\n echo \"${!x}\"\n done\n}\n\nf a b c\n\n# output:\n# a: 1,4\n# b: 2,3\n# c: 3\n</code></pre>"},{"location":"syntax/ccmd/case/#portability-considerations","title":"Portability considerations","text":"<ul> <li>Only the <code>;;</code> delimiter is specified by POSIX.</li> <li>zsh and mksh use the <code>;|</code> control operator instead of Bash's <code>;;&amp;</code>. Mksh has <code>;;&amp;</code> for Bash compatability (undocumented).</li> <li>ksh93 has the <code>;&amp;</code> operator, but no <code>;;&amp;</code> or equivalent.</li> <li>ksh93, mksh, zsh, and posh support a historical syntax where open and close braces may be used in place of <code>in</code> and <code>esac</code>: <code>case word { x) ...; };</code>. This is similar to the alternate form Bash supports for its for loops, but Bash doesn't support this syntax for <code>case..esac</code>.</li> </ul>"},{"location":"syntax/ccmd/case/#see-also","title":"See also","text":"<ul> <li>POSIX case conditional construct</li> </ul>"},{"location":"syntax/ccmd/classic_for/","title":"The classic for-loop","text":""},{"location":"syntax/ccmd/classic_for/#synopsis","title":"Synopsis","text":"<pre><code>for &lt;NAME&gt;; do\n &lt;LIST&gt;\ndone\n\nfor &lt;NAME&gt; in &lt;WORDS&gt;; do\n &lt;LIST&gt;\ndone\n</code></pre> <p>alternative, historical and undocumented syntax <sup>1</sup></p> <pre><code>for &lt;NAME&gt;; {\n &lt;LIST&gt;\n}\n\nfor &lt;NAME&gt; in &lt;WORDS&gt;; {\n &lt;LIST&gt;\n}\n</code></pre>"},{"location":"syntax/ccmd/classic_for/#description","title":"Description","text":"<p>For every word in <code>&lt;WORDS&gt;</code>, one iteration of the loop is performed and the variable <code>&lt;NAME&gt;</code> is set to the current word. If no \"<code>in &lt;WORDS&gt;</code>\" is present to give an own word-list, then the positional parameters (<code>\"$@\"</code>) are used (the arguments to the script or function). In this case (and only in this case), the semicolon between the variable name and the <code>do</code> is optional.</p> <p>If you use the loop-variable inside the for-loop and it can contain spaces, you need to quote it, since normal word-splitting procedures apply.</p> <p>:!: Like all loops (both <code>for</code>-loops, <code>while</code> and <code>until</code>), this loop can be</p> <ul> <li>terminated (broken) by the <code>break</code> command, optionally as <code>break N</code> to break <code>N</code> levels of nested loops</li> <li>forced to immediately do the next iteration using the <code>continue</code> command, optionally as <code>continue N</code> analog to <code>break N</code></li> </ul> <p>Bash knows an alternative syntax for the <code>for</code> loop, enclosing the loop body in <code>{...}</code> instead of <code>do ... done</code>:</p> <pre><code>for x in 1 2 3\n{\n echo $x\n}\n</code></pre> <p>This syntax is not documented and should not be used. I found the parser definitions for it in 1.x code, and in modern 4.x code. My guess is that it's there for compatiblity reasons. This syntax is not specified by POSIX\u00ae.</p>"},{"location":"syntax/ccmd/classic_for/#return-status","title":"Return status","text":"<p>The return status is the one of the last command executed in <code>&lt;LIST&gt;</code> or <code>0</code> (<code>TRUE</code>), if the item list <code>&lt;WORDS&gt;</code> evaluates to nothing (i.e.: \"is empty\"!).</p>"},{"location":"syntax/ccmd/classic_for/#examples","title":"Examples","text":""},{"location":"syntax/ccmd/classic_for/#iterate-over-array-elements","title":"Iterate over array elements","text":"<p>With some array syntax (see arrays) you can easily \"feed\" the for-loop to iterate over all elements in an array (by mass-expanding all elements):</p> <pre><code>for element in \"${myarray[@]}\"; do\n echo \"Element: $element\"\ndone\n</code></pre> <p>Another way is to mass-expand all used indexes and access the array by index:</p> <pre><code>for index in \"${!myarray[@]}\"; do\n echo \"Element[$index]: ${myarray[$index]}\"\ndone\n</code></pre>"},{"location":"syntax/ccmd/classic_for/#list-positional-parameters","title":"List positional parameters","text":"<p>You can use this function to test how arguments to a command will be interpreted and parsed, and finally used:</p> <pre><code>argtest() {\n n=1\n for arg; do\n echo \"Argument $((n++)): \\\"$arg\\\"\"\n done\n}\n</code></pre>"},{"location":"syntax/ccmd/classic_for/#loop-through-a-directory","title":"Loop through a directory","text":"<p>Since pathname expansion will expand all filenames to separate words, regardless of spaces, you can use the for-loop to iterate through filenames in a directory:</p> <pre><code>for fn in *; do\n if [ -h \"$fn\" ]; then\n echo -n \"Symlink: \"\n elif [ -d \"$fn\" ]; then\n echo -n \"Dir: \"\n elif [ -f \"$fn\" ]; then\n echo -n \"File: \"\n else\n echo -n \"Unknown: \"\n fi\n echo \"$fn\"\ndone\n</code></pre> <p>Stupid example, I know ;-)</p>"},{"location":"syntax/ccmd/classic_for/#loop-over-lines-of-output","title":"Loop over lines of output","text":"<p>To be complete: You can change the internal field separator (IFS) to a newline and thus make a for-loop iterating over lines instead of words:</p> <pre><code>IFS=$'\\n'\nfor f in $(ls); do\n echo $f\ndone\n</code></pre> <p>This is just an example. In general</p> <ul> <li>it's not a good idea to parse <code>ls(1)</code> output</li> <li>the while loop (using the <code>read</code> command) is a better joice to iterate over lines</li> </ul>"},{"location":"syntax/ccmd/classic_for/#nested-for-loops","title":"Nested for-loops","text":"<p>It's of course possible to use another for-loop as <code>&lt;LIST&gt;</code>. Here, counting from 0 to 99 in a weird way:</p> <pre><code>for x in 0 1 2 3 4 5 6 7 8 9; do\n for y in 0 1 2 3 4 5 6 7 8 9; do\n echo $x$y\n done\ndone\n</code></pre>"},{"location":"syntax/ccmd/classic_for/#loop-over-a-number-range","title":"Loop over a number range","text":"<p>Beginning in Bash 4, you can also use \"sequence expression\" form of brace expansion syntax when looping over numbers, and this form does not create leading zeroes unless you ask for them:</p> <pre><code># 100 numbers, no leading zeroes\nfor x in {0..99}; do\n echo $x\ndone\n</code></pre> <pre><code># Every other number, width 3\nfor x in {000..99..2}; do\n echo $x\ndone\n</code></pre> <p>WARNING: the entire list is created before looping starts. If your list is huge this may be an issue, but no more so than for a glob that expands to a huge list.</p>"},{"location":"syntax/ccmd/classic_for/#portability-considerations","title":"Portability considerations","text":""},{"location":"syntax/ccmd/classic_for/#see-also","title":"See also","text":"<ul> <li>c_for</li> </ul> <ol> <li> <p>http://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xcu_chap02.html#tag_23_02_09_12 \u21a9</p> </li> </ol>"},{"location":"syntax/ccmd/conditional_expression/","title":"The conditional expression","text":""},{"location":"syntax/ccmd/conditional_expression/#synopsis","title":"Synopsis","text":"<pre><code>[[ &lt;EXPRESSION&gt; ]]\n</code></pre>"},{"location":"syntax/ccmd/conditional_expression/#description","title":"Description","text":"<p>The conditional expression is meant as the modern variant of the classic test command. Since it is not a normal command, Bash doesn't need to apply the normal commandline parsing rules like recognizing <code>&amp;&amp;</code> as command list operator.</p> <p>The testing features basically are the same (see the lists for classic test command), with some additions and extensions.</p> Operator Description <code>( &lt;EXPRESSION&gt; )</code> Used to group expressions, to influence precedence of operators <code>&lt;EXPRESSION1&gt; &amp;&amp; &lt;EXPRESSION2&gt;</code> <code>TRUE</code> if <code>&lt;EXPRESSION1&gt;</code>and<code>&lt;EXPRESSION2&gt;</code> are <code>TRUE</code> (do not use <code>-a</code>!) <code>&lt;EXPRESSION1&gt;||&lt;EXPRESSION2&gt;</code> <code>TRUE</code> if <code>&lt;EXPRESSION1&gt;</code>or<code>&lt;EXPRESSION2&gt;</code> is <code>TRUE</code> (do not use <code>-o</code>!) <code>&lt;STRING&gt; == &lt;PATTERN&gt;</code> <code>&lt;STRING&gt;</code> is checked against the pattern <code>&lt;PATTERN&gt;</code> - <code>TRUE</code> on a matchBut note\u00b9, quoting the pattern forces a literal comparison. <code>&lt;STRING&gt; = &lt;PATTERN&gt;</code> equivalent to the <code>==</code> operator <code>&lt;STRING&gt; != &lt;PATTERN&gt;</code> <code>&lt;STRING&gt;</code> is checked against the pattern <code>&lt;PATTERN&gt;</code> - <code>TRUE</code> on no match <code>&lt;STRING&gt; =~ &lt;ERE&gt;</code> <code>&lt;STRING&gt;</code> is checked against the extended regular expression <code>&lt;ERE&gt;</code> - <code>TRUE</code> on a match See the classic test operators Do not use the <code>test</code>-typical operators <code>-a</code> and <code>-o</code> for AND and OR. See also arithmetic comparisons Using <code>(( &lt;EXPRESSION&gt; ))</code>, the arithmetic expression compound command <p>When the <code>==</code> and <code>!=</code> operators are used, the string to the right of the operator is considered a pattern and matched according to the rules of Pattern Matching. If the shell option <code>nocasematch</code> is enabled, the match is performed without regard to the case of alphabetic characters.</p> <p>\u00b9Any part of the pattern may be quoted to force it to be matched as a literal string.</p> <p>When the operators <code>&lt;</code> and <code>&gt;</code> are used (string collation order), the test happens using the current locale when the <code>compat</code> level is greater than \"40\".</p> <p>Operator precedence (highest =&gt; lowest):</p> <ul> <li><code>( &lt;EXPRESSION&gt; )</code></li> <li><code>! &lt;EXPRESSION&gt;</code></li> <li><code>&lt;EXPRESSION1&gt; &amp;&amp; &lt;EXPRESSION2&gt;</code></li> <li><code>&lt;EXPRESSION1&gt; || &lt;EXPRESSION2&gt;</code></li> </ul> <p>Do not use the <code>test</code>-typical operators <code>-a</code> and <code>-o</code> for AND and OR, they are not known to the conditional expression. Instead, use the operators <code>&amp;&amp;</code> and <code>||</code>.</p>"},{"location":"syntax/ccmd/conditional_expression/#word-splitting","title":"Word splitting","text":"<p>Word splitting and pathname expansion are not performed in the expression you give. That means, a variable containing spaces can be used without quoting:</p> <pre><code>sentence=\"Be liberal in what you accept, and conservative in what you send\"\ncheckme=\"Be liberal in what you accept, and conservative in what you send\"\nif [[ $sentence == $checkme ]]; then\n echo \"Matched...!\"\nelse\n echo \"Sorry, no match :-(\"\nfi\n</code></pre> <p>Compare that to the classic test command, where word splitting is done (because it's a normal command, not something special):</p> <pre><code>sentence=\"Be liberal in what you accept, and conservative in what you send\"\ncheckme=\"Be liberal in what you accept, and conservative in what you send\"\nif [ \"$sentence\" == \"$checkme\" ]; then\n echo \"Matched...!\"\nelse\n echo \"Sorry, no match :-(\"\nfi\n</code></pre> <p>You need to quote that variable reference in the classic test command, since (due to the spaces) the word splitting will break it otherwise!</p>"},{"location":"syntax/ccmd/conditional_expression/#regular-expression-matching","title":"Regular Expression Matching","text":"<p>Using the operator <code>=~</code>, the left hand side operand is matched against the extended regular expression (ERE) on the right hand side.</p> <p>This is consistent with matching against patterns: Every quoted part of the regular expression is taken literally, even if it contains regular expression special characters.</p> <p>Best practise is to put the regular expression to match against into a variable. This is to avoid shell parsing errors on otherwise valid regular expressions.</p> <pre><code>REGEX=\"^[[:upper:]]{2}[[:lower:]]*$\"\n\n# Test 1\nSTRING=Hello\nif [[ $STRING =~ $REGEX ]]; then\n echo \"Match.\"\nelse\n echo \"No match.\"\nfi\n# ==&gt; \"No match.\"\n\n# Test 2\nSTRING=HEllo\nif [[ $STRING =~ $REGEX ]]; then\n echo \"Match.\"\nelse\n echo \"No match.\"\nfi\n# ==&gt; \"Match.\"\n</code></pre> <p>The interpretation of quoted regular expression special characters can be influenced by setting the <code>compat31</code> and <code>compat32</code> shell options (<code>compat*</code> in general). See shell_options.</p>"},{"location":"syntax/ccmd/conditional_expression/#the-special-bash_rematch-array-variable","title":"The special BASH_REMATCH array variable","text":"<p>An array variable whose members are assigned by the <code>=~</code> binary operator to the <code>[[</code> conditional command.</p> <p>The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the nth parenthesized subexpression.</p> <p>See BASH_REMATCH.</p> <p>Example:</p> <pre><code>if [[ \"The quick, red fox\" =~ ^The\\ (.*),\\ (.*)\\ fox$ ]]; then\n echo \"${BASH_REMATCH[0]} is ${BASH_REMATCH[1]} and ${BASH_REMATCH[2]}.\";\nfi\n\n==&gt; The quick, red fox is quick and red.\n</code></pre>"},{"location":"syntax/ccmd/conditional_expression/#behaviour-differences-compared-to-the-builtin-test-command","title":"Behaviour differences compared to the builtin test command","text":"<p>As of Bash 4.1 alpha, the test primaries '&lt;' and '&gt;' (compare strings lexicographically) use the current locale settings, while the same primitives for the builtin test command don't. This leads to the following situation where they behave differently:</p> <pre><code>$ ./cond.sh\n[[ ' 4' &lt; '1' ]] --&gt; exit 1\n[[ 'step+' &lt; 'step-' ]] --&gt; exit 1\n[ ' 4' &lt; '1' ] --&gt; exit 0\n[ 'step+' &lt; 'step-' ] --&gt; exit 0\n</code></pre> <p>It won't be aligned. The conditional expression continues to respect the locate, as introduced with 4.1-alpha, the builtin <code>test</code>/<code>[</code> command continues to behave differently.</p>"},{"location":"syntax/ccmd/conditional_expression/#implicit-arithmetic-context","title":"Implicit arithmetic context","text":"<p>When you use a numeric comparison, the arguments are evaluated as an arithmetic expression. The arithmetic expression must be quoted if it both contains whitespace and is not the result of an expansion.</p> <pre><code>[[ 'i=5, i+=2' -eq 3+4 ]] &amp;&amp; echo true # prints true.\n</code></pre>"},{"location":"syntax/ccmd/conditional_expression/#examples","title":"Examples","text":""},{"location":"syntax/ccmd/conditional_expression/#portability-considerations","title":"Portability considerations","text":"<ul> <li><code>[[ ... ]]</code> functionality isn't specified by POSIX(R), though it's a reserved word</li> <li>Amongst the major \"POSIX-shell superset languages\" (for lack of a better term) which do have <code>[[</code>, the test expression compound command is one of the very most portable non-POSIX features. Aside from the <code>=~</code> operator, almost every major feature is consistent between Ksh88, Ksh93, mksh, Zsh, and Bash. Ksh93 also adds a large number of unique pattern matching features not supported by other shells including support for several different regex dialects, which are invoked using a different syntax from Bash's <code>=~</code>, though <code>=~</code> is still supported by ksh and defaults to ERE.</li> <li>As an extension to POSIX ERE, most GNU software supports backreferences in ERE, including Bash. According to POSIX, only BRE is supposed to support them. This requires Bash to be linked against glibc, so it won't necessarily work on all platforms. For example, <code>$(m='(abc(def))(\\1)(\\2)'; [[ abcdefabcdefdef =~ $m ]]; printf '&lt;%s&gt; ' $? \"${BASH_REMATCH[@]}\" )</code> will give <code>&lt;0&gt; &lt;abcdefabcdefdef&gt; &lt;abcdef&gt; &lt;def&gt; &lt;abcdef&gt; &lt;def&gt;</code>.</li> <li>the <code>=~</code> (regex) operator was introduced in Bash 3.0, and its behaviour changed in Bash 3.2: since 3.2, quoted strings and substrings are matched as literals by default.</li> <li>the behaviour of the <code>&lt;</code> and <code>&gt;</code> operators (string collation order) has changed since Bash 4.0</li> </ul>"},{"location":"syntax/ccmd/conditional_expression/#see-also","title":"See also","text":"<ul> <li>Internal: pattern matching language</li> <li>Internal: the classic test command</li> <li>Internal: the if-clause</li> <li>What is the difference between test, [ and [[ ? - BashFAQ 31 - Greg's wiki.</li> </ul>"},{"location":"syntax/ccmd/grouping_plain/","title":"Grouping commands","text":""},{"location":"syntax/ccmd/grouping_plain/#synopsis","title":"Synopsis","text":"<pre><code>{ &lt;LIST&gt;; }\n\n{\n&lt;LIST&gt;\n}\n</code></pre>"},{"location":"syntax/ccmd/grouping_plain/#description","title":"Description","text":"<p>The list <code>&lt;LIST&gt;</code> is simply executed in the current shell environment. The list must be terminated with a newline or semicolon. For parsing reasons, the curly braces must be separated from <code>&lt;LIST&gt;</code> by a semicolon and blanks if they're in the same line! <sup>1</sup><sup>2</sup></p> <p>This is known as a group command. The return status is the exit status (exit code) of the list.</p> <p>The input and output filedescriptors are cumulative:</p> <pre><code>{\n echo \"PASSWD follows\"\n cat /etc/passwd\n echo\n echo \"GROUPS follows\"\n cat /etc/group\n} &gt;output.txt\n</code></pre> <p>This compound command also usually is the body of a function definition, though not the only compound command that's valid there:</p> <pre><code>print_help() {\n echo \"Options:\"\n echo \"-h This help text\"\n echo \"-f FILE Use config file FILE\"\n echo \"-u USER Run as user USER\"\n}\n</code></pre>"},{"location":"syntax/ccmd/grouping_plain/#examples","title":"Examples","text":""},{"location":"syntax/ccmd/grouping_plain/#a-try-catch-block","title":"A Try-Catch block","text":"<pre><code> try_catch() {\n { # Try-block:\n eval \"$@\"\n } ||\n { # Catch-block:\n echo \"An error occurred\"\n return -1\n }\n }\n</code></pre>"},{"location":"syntax/ccmd/grouping_plain/#portability-considerations","title":"Portability considerations","text":""},{"location":"syntax/ccmd/grouping_plain/#see-also","title":"See also","text":"<pre><code> * [[syntax:ccmd:grouping_subshell | grouping commands in a subshell]]\n</code></pre> <ol> <li> <p>Actually any properly terminated compound command will work without extra separator (also in some other shells), example: <code>{ while sleep 1; do echo ZzZzzZ; done }</code> is valid. But this is not documented, infact the documentation explicitly says that a semicolon or a newline must separate the enclosed list. -- thanks <code>geirha</code> at Freenode\u00a0\u21a9</p> </li> <li> <p>The main reason is the fact that in shell grammar, the curly braces are not control operators but reserved words -- TheBonsai\u00a0\u21a9</p> </li> </ol>"},{"location":"syntax/ccmd/grouping_subshell/","title":"Grouping commands in a subshell","text":""},{"location":"syntax/ccmd/grouping_subshell/#synopsis","title":"Synopsis","text":"<pre><code>( &lt;LIST&gt; )\n</code></pre>"},{"location":"syntax/ccmd/grouping_subshell/#description","title":"Description","text":"<p>The list <code>&lt;LIST&gt;</code> is executed in a separate shell - a subprocess. No changes to the environment (variables etc...) are reflected in the \"main shell\".</p>"},{"location":"syntax/ccmd/grouping_subshell/#examples","title":"Examples","text":"<p>Execute a command in a different directory.</p> <pre><code>echo \"$PWD\"\n( cd /usr; echo \"$PWD\" )\necho \"$PWD\" # Still in the original directory.\n</code></pre>"},{"location":"syntax/ccmd/grouping_subshell/#portability-considerations","title":"Portability considerations","text":"<ul> <li>The subshell compound command is specified by POSIX.</li> <li>Avoid ambiguous syntax.</li> </ul> <pre><code>(((1+1))) # Equivalent to: (( (1+1) ))\n</code></pre>"},{"location":"syntax/ccmd/grouping_subshell/#see-also","title":"See also","text":"<ul> <li>grouping commands</li> <li>Subshells on Greycat's wiki</li> </ul>"},{"location":"syntax/ccmd/if_clause/","title":"The if-clause","text":""},{"location":"syntax/ccmd/if_clause/#synopsis","title":"Synopsis","text":"<pre><code>if &lt;LIST&gt;; then\n &lt;LIST&gt;\nfi\n\nif &lt;LIST&gt;; then\n &lt;LIST&gt;\nelse\n &lt;LIST&gt;\nfi\n\nif &lt;LIST&gt;; then\n &lt;LIST&gt;\nelif &lt;LIST&gt;; then\n &lt;LIST&gt;\nelse\n &lt;LIST&gt;\nfi\n</code></pre>"},{"location":"syntax/ccmd/if_clause/#description","title":"Description","text":"<p>The <code>if</code>-clause can control the script's flow (what's executed) by looking at the exit codes of other commands.</p> <p>All commandsets <code>&lt;LIST&gt;</code> are interpreted as command lists, thus they can contain the whole palette from simple commands over pipelines to compound commands (and their combination) as condition.</p>"},{"location":"syntax/ccmd/if_clause/#operation","title":"Operation","text":"<p>The <code>if &lt;LIST&gt;</code> commands are executed. If the exit code was 0 (TRUE) then the <code>then &lt;LIST&gt;</code> commands are executed, otherwise the <code>elif &lt;LIST&gt;</code> commands and their <code>then &lt;LIST&gt;</code> statements are executed in turn, if all down to the last one fails, the <code>else &lt;LIST&gt;</code> commands are executed, if one of the <code>elif</code> succeeds, its <code>then</code> thread is executed, and the <code>if</code>-clause finishes.</p> <p>Basically, the <code>elif</code> clauses are just additional conditions to test (like a chain of conditions) if the very first condition failed. If one of the conditions fails, the <code>else</code> commands are executed, otherwise the commands of the condition that succeeded.</p>"},{"location":"syntax/ccmd/if_clause/#examples","title":"Examples","text":"<p>Check if a specific user exists in /etc/passwd :-)</p> <pre><code>if grep ^myuser: /etc/passwd &gt;/dev/null 2&gt;&amp;1; then\n echo \"Yes, it seems I'm real\"\nelse\n echo \"Uh - am I a ghost?\"\nfi\n</code></pre> <p>Mount with check</p> <pre><code>if ! mount /mnt/backup &gt;/dev/null 2&gt;&amp;1; then\n echo \"FATAL: backup mount failed\" &gt;&amp;2\n exit 1\nfi\n</code></pre> <p>Multiple commands as condition</p> <p>It's perfectly valid to do:</p> <pre><code>if echo \"I'm testing!\"; [ -e /some/file ]; then\n ...\nfi\n</code></pre> <p>The exit code that dictates the condition's value is the exit code of the very last command executed in the condition-list (here: The <code>[ -e /some/file ]</code>)</p> <p>A complete pipe as condition</p> <p>A complete pipe can also be used as condition. It's very similar to the example above (multiple commands):</p> <pre><code>if echo \"Hello world!\" | grep -i hello &gt;/dev/null 2&gt;&amp;1; then\n echo \"You just said 'hello', yeah?\"\nfi\n</code></pre>"},{"location":"syntax/ccmd/if_clause/#portability-considerations","title":"Portability considerations","text":""},{"location":"syntax/ccmd/if_clause/#see-also","title":"See also","text":"<ul> <li>Internal: the classic test command</li> </ul>"},{"location":"syntax/ccmd/intro/","title":"Bash compound commands","text":"<p>The main part of Bash's syntax are the so-called compound commands. They're called like that because they use \"real\" commands (simple commands or lists) and knit some intelligence around them. That is what the essential \"Bash language\" is made of.</p>"},{"location":"syntax/ccmd/intro/#command-grouping","title":"Command grouping","text":"<ul> <li>grouping: command grouping</li> <li>grouping again: command grouping in a subshell</li> </ul>"},{"location":"syntax/ccmd/intro/#conditional-reactions","title":"Conditional reactions","text":"<p>Note that conditionals can also be scripted using list, which are syntax elements, not commands.</p> <ul> <li>the \"new\" test command: conditional expression</li> <li>if-clause: conditional branching</li> <li>case statement: pattern-based branching</li> </ul>"},{"location":"syntax/ccmd/intro/#loops","title":"Loops","text":"<ul> <li>classic for-loop</li> <li>C-style for-loop</li> <li>while loop</li> <li>until loop</li> </ul>"},{"location":"syntax/ccmd/intro/#misc","title":"Misc","text":"<ul> <li>math: arithmetic evaluation</li> <li>menus: user selections</li> </ul>"},{"location":"syntax/ccmd/until_loop/","title":"The until loop","text":""},{"location":"syntax/ccmd/until_loop/#synopsis","title":"Synopsis","text":"<pre><code>until &lt;LIST1&gt; ; do\n &lt;LIST2&gt;\ndone\n</code></pre>"},{"location":"syntax/ccmd/until_loop/#description","title":"Description","text":"<p>The until-loop is relatively simple in what it does: it executes the command list <code>&lt;LIST1&gt;</code> and if the exit code of it was not 0 (FALSE) it executes <code>&lt;LIST2&gt;</code>. This happens again and again until <code>&lt;LIST1&gt;</code> returns TRUE.</p> <p>This is exactly the opposite of the while loop.</p> <p>:!: Like all loops (both <code>for</code>-loops, <code>while</code> and <code>until</code>), this loop can be</p> <ul> <li>terminated (broken) by the <code>break</code> command, optionally as <code>break N</code> to break <code>N</code> levels of nested loops</li> <li>forced to immediately do the next iteration using the <code>continue</code> command, optionally as <code>continue N</code> analog to <code>break N</code></li> </ul>"},{"location":"syntax/ccmd/until_loop/#return-status","title":"Return status","text":"<p>The return status is the one of the last command executed in <code>&lt;LIST2&gt;</code>, or <code>0</code> (<code>TRUE</code>) if none was executed.</p>"},{"location":"syntax/ccmd/until_loop/#examples","title":"Examples","text":""},{"location":"syntax/ccmd/until_loop/#portability-considerations","title":"Portability considerations","text":""},{"location":"syntax/ccmd/until_loop/#see-also","title":"See also","text":"<ul> <li>Internal: The while loop</li> </ul>"},{"location":"syntax/ccmd/user_select/","title":"User selections","text":""},{"location":"syntax/ccmd/user_select/#synopsis","title":"Synopsis","text":"<pre><code>select &lt;NAME&gt;; do\n &lt;LIST&gt;\ndone\n\nselect &lt;NAME&gt; in &lt;WORDS&gt;; do\n &lt;LIST&gt;\ndone\n\n# alternative, historical and undocumented syntax\n\nselect &lt;NAME&gt;\n{\n &lt;LIST&gt;\n}\n\nselect &lt;NAME&gt; in &lt;WORDS&gt;\n{\n &lt;LIST&gt;\n}\n</code></pre>"},{"location":"syntax/ccmd/user_select/#description","title":"Description","text":"<p>This compound command provides a kind of menu. The user is prompted with a numbered list of the given words, and is asked to input the index number of the word. If a word was selected, the variable <code>&lt;NAME&gt;</code> is set to this word, and the list <code>&lt;LIST&gt;</code> is executed.</p> <p>If no <code>in &lt;WORDS&gt;</code> is given, then the positional parameters are taken as words (as if <code>in \"$@\"</code> was written).</p> <p>Regardless of the functionality, the number the user entered is saved in the variable <code>REPLY</code>.</p> <p>Bash knows an alternative syntax for the <code>select</code> command, enclosing the loop body in <code>{...}</code> instead of <code>do ... done</code>:</p> <pre><code>select x in 1 2 3\n{\n echo $x\n}\n</code></pre> <p>This syntax is not documented and should not be used. I found the parser definitions for it in 1.x code, and in modern 4.x code. My guess is that it's there for compatiblity reasons. This syntax is not specified by POSIX(R).</p>"},{"location":"syntax/ccmd/user_select/#examples","title":"Examples","text":"<pre><code># select &lt;NAME&gt; in &lt;WORDS&gt;; do\n# &lt;LIST&gt;\n# done\n\n\n# meaning e.g.:\n\nclear\necho\necho hit number key 1 2 or 3 then ENTER-key\necho ENTER alone is an empty choice and will loop endlessly until Ctrl-C or Ctrl-D\necho\n\nselect OPTIONX in beer whiskey wine liquor ; do\n\n echo you ordered a $OPTIONX\n break # break avoids endless loop -- second line to be executed always\n\ndone\n\n# place some if else fi business here\n# and explain how it makes sense that $OPTIONX is red but OPTIONX is black \n# even though both are variables\n</code></pre>"},{"location":"syntax/ccmd/user_select/#portability-considerations","title":"Portability considerations","text":""},{"location":"syntax/ccmd/user_select/#see-also","title":"See also","text":""},{"location":"syntax/ccmd/while_loop/","title":"The while-loop","text":""},{"location":"syntax/ccmd/while_loop/#synopsis","title":"Synopsis","text":"<pre><code>while &lt;LIST1&gt; ; do\n &lt;LIST2&gt;\ndone\n</code></pre>"},{"location":"syntax/ccmd/while_loop/#description","title":"Description","text":"<p>The while-loop is relatively simple in what it does: it executes the command list <code>&lt;LIST1&gt;</code> and if the exit code of it was 0 (TRUE) it executes <code>&lt;LIST2&gt;</code>. This happens again and again until <code>&lt;LIST1&gt;</code> returns FALSE.</p> <p>This is exactly the opposite of the until loop.</p> <p>:!: Like all loops (both <code>for</code>-loops, <code>while</code> and <code>until</code>), this loop can be</p> <ul> <li>terminated (broken) by the <code>break</code> command, optionally as <code>break N</code> to break <code>N</code> levels of nested loops</li> <li>forced to immediately do the next iteration using the <code>continue</code> command, optionally as <code>continue N</code> analog to <code>break N</code></li> </ul>"},{"location":"syntax/ccmd/while_loop/#return-status","title":"Return status","text":"<p>The return status is the one of the last command executed in <code>&lt;LIST2&gt;</code>, or <code>0</code> (<code>TRUE</code>) if none was executed.</p>"},{"location":"syntax/ccmd/while_loop/#examples","title":"Examples","text":""},{"location":"syntax/ccmd/while_loop/#portability-considerations","title":"Portability considerations","text":""},{"location":"syntax/ccmd/while_loop/#see-also","title":"See also","text":"<ul> <li>Internal: The until loop</li> <li>Internal: code examples of the read builtin command to see how you can loop over lines</li> </ul>"},{"location":"syntax/expansion/arith/","title":"Arithmetic expansion","text":"<pre><code>$(( &lt;EXPRESSION&gt; ))\n\n$[ &lt;EXPRESSION&gt; ]\n</code></pre> <p>The arithmetic expression <code>&lt;EXPRESSION&gt;</code> is evaluated and expands to the result. The output of the arithmetic expansion is guaranteed to be one word and a digit in Bash.</p> <p>Please do not use the second form <code>$[ ... ]</code>! It's deprecated. The preferred and standardized form is <code>$(( ... ))</code>!</p> <p>Example</p> <pre><code>function printSum {\n typeset -A args\n typeset name\n for name in first second; do\n [[ -t 0 ]] &amp;&amp; printf 'Enter %s positive integer: ' \"$name\" &gt;&amp;2\n read -r ${BASH_VERSION+-e} \"args[$name]\"\n [[ ${args[$name]} == +([[:digit:]]) ]] || return 1 # Validation is extremely important whenever user input is used in arithmetic.\n done\n printf 'The sum is %d.' $((${args[first]} + ${args[second]}))\n}\n</code></pre> <p>Note that in Bash you don't need the arithmetic expansion to check for the boolean value of an arithmetic expression. This can be done using the arithmetic evaluation compound command:</p> <pre><code>printf %s 'Enter a number: ' &gt;&amp;2\nread -r number\nif ((number == 1234)); then\n echo 'Good guess'\nelse\n echo 'Haha... :-P'\nfi\n</code></pre> <p>Variables used inside the arithmetic expansion, as in all arithmetic contexts, can be used with or without variable expansion:</p> <pre><code>x=1\n\necho $((x)) # Good.\necho $(($x)) # Ok. Avoid expansions within arithmetic. Use variables directly.\necho $((\"$x\")) # Error. There is no quote-removal in arithmetic contexts. It expands to $((\"1\")), which is an invalid arithmetic expression.\necho $((x[0])) # Good.\necho $((${x[0]})) # Ok. Nested expansion again.\necho $((${x[$((${x[!$x]}-$x))]})) # Same as above but more ridiculous.\necho $(($x[0])) # Error. This expands to $((1[0])), an invalid expression.\n</code></pre>"},{"location":"syntax/expansion/arith/#bugs-and-portability-considerations","title":"Bugs and Portability considerations","text":"<ul> <li>The original Bourne shell doesn't have arithmetic expansions. You have to use something like <code>expr(1)</code> within backticks instead. Since <code>expr</code> is horrible (as are backticks), and arithmetic expansion is required by POSIX, you should not worry about this, and preferably fix any code you find that's still using <code>expr</code>.</li> </ul>"},{"location":"syntax/expansion/arith/#see-also","title":"See also","text":"<ul> <li>arithmetic expressions</li> <li>arithmetic evaluation compound command</li> <li>Introduction to expansion and substitution</li> <li>POSIX definition</li> </ul>"},{"location":"syntax/expansion/brace/","title":"Brace expansion","text":"<pre><code>{string1,string2,...,stringN}\n{&lt;START&gt;..&lt;END&gt;}\n\n{&lt;START&gt;..&lt;END&gt;..&lt;INCR&gt;} (Bash 4)\n\n&lt;PREFIX&gt;{........}\n\n{........}&lt;SUFFIX&gt;\n\n&lt;PREFIX&gt;{........}&lt;SUFFIX&gt;\n</code></pre> <p>Brace expansion is used to generate arbitrary strings. The specified strings are used to generate all possible combinations with the optional surrounding prefixes and suffixes.</p> <p>Usually it's used to generate mass-arguments for a command, that follow a specific naming-scheme.</p> <p>:!: It is the very first step in expansion-handling, it's important to understand that. When you use</p> <pre><code>echo {a,b}$PATH\n</code></pre> <p>then the brace expansion does not expand the variable - this is done in a later step. Brace expansion just makes it being:</p> <pre><code>echo a$PATH b$PATH\n</code></pre> <p>Another common pitfall is to assume that a range like <code>{1..200}</code> can be expressed with variables using <code>{$a..$b}</code>. Due to what I described above, it simply is not possible, because it's the very first step in doing expansions. A possible way to achieve this, if you really can't handle this in another way, is using the <code>eval</code> command, which basically evaluates a commandline twice: <code>eval echo {$a..$b}</code> For instance, when embedded inside a for loop : <code>for i in $(eval echo {$a..$b})</code> This requires that the entire command be properly escaped to avoid unexpected expansions. If the sequence expansion is to be assigned to an array, another method is possible using declaration commands: <code>declare -a 'pics=(img{'\"$a..$b\"'}.png)'; mv \"${pics[@]}\" ../imgs</code> This is significantly safer, but one must still be careful to control the values of <code>$a</code> and <code>$b</code>. Both the exact quoting, and explicitly including \"<code>-a</code>\" are important.</p> <p>The brace expansion is present in two basic forms, string lists and ranges.</p> <p>It can be switched on and off under runtime by using the <code>set</code> builtin and the option <code>-B</code> and <code>+B</code> or the long option <code>braceexpand</code>. If brace expansion is enabled, the stringlist in <code>SHELLOPTS</code> contains <code>braceexpand</code>.</p>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#string-lists","title":"String lists","text":"<pre><code>{string1,string2,...,stringN}\n</code></pre> <p>Without the optional prefix and suffix strings, the result is just a space-separated list of the given strings:</p> <pre><code>$ echo {I,want,my,money,back}\nI want my money back\n</code></pre> <p>With prefix or suffix strings, the result is a space-separated list of all possible combinations of prefix or suffix specified strings:</p> <pre><code>$ echo _{I,want,my,money,back}\n_I _want _my _money _back\n\n$ echo {I,want,my,money,back}_\nI_ want_ my_ money_ back_\n\n$ echo _{I,want,my,money,back}-\n_I- _want- _my- _money- _back-\n</code></pre> <p>The brace expansion is only performed, if the given string list is really a list of strings, i.e., if there is a minimum of one \"<code>,</code>\" (comma)! Something like <code>{money}</code> doesn't expand to something special, it's really only the text \"<code>{money}</code>\".</p>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#ranges","title":"Ranges","text":"<pre><code>{&lt;START&gt;..&lt;END&gt;}\n</code></pre> <p>Brace expansion using ranges is written giving the startpoint and the endpoint of the range. This is a \"sequence expression\". The sequences can be of two types</p> <ul> <li>integers (optionally zero padded, optionally with a given increment)</li> <li> <p>characters</p> <p>$ echo {5..12} 5 6 7 8 9 10 11 12</p> <p>$ echo {c..k} c d e f g h i j k</p> </li> </ul> <p>When you mix these both types, brace expansion is not performed:</p> <pre><code>$ echo {5..k}\n{5..k}\n</code></pre> <p>When you zero pad one of the numbers (or both) in a range, then the generated range is zero padded, too:</p> <pre><code>$ echo {01..10}\n01 02 03 04 05 06 07 08 09 10\n</code></pre> <p>There's a chapter of Bash 4 brace expansion changes at the end of this article.</p> <p>Similar to the expansion using stringlists, you can add prefix and suffix strings:</p> <pre><code>$ echo 1.{0..9}\n1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9\n\n$ echo ---{A..E}---\n---A--- ---B--- ---C--- ---D--- ---E---\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#combining-and-nesting","title":"Combining and nesting","text":"<p>When you combine more brace expansions, you effectively use a brace expansion as prefix or suffix for another one. Let's generate all possible combinations of uppercase letters and digits:</p> <pre><code>$ echo {A..Z}{0..9}\nA0 A1 A2 A3 A4 A5 A6 A7 A8 A9 B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 C0 C1 C2 C3 C4 C5 C6\nC7 C8 C9 D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 F0 F1 F2 F3\nF4 F5 F6 F7 F8 F9 G0 G1 G2 G3 G4 G5 G6 G7 G8 G9 H0 H1 H2 H3 H4 H5 H6 H7 H8 H9 I0\nI1 I2 I3 I4 I5 I6 I7 I8 I9 J0 J1 J2 J3 J4 J5 J6 J7 J8 J9 K0 K1 K2 K3 K4 K5 K6 K7\nK8 K9 L0 L1 L2 L3 L4 L5 L6 L7 L8 L9 M0 M1 M2 M3 M4 M5 M6 M7 M8 M9 N0 N1 N2 N3 N4\nN5 N6 N7 N8 N9 O0 O1 O2 O3 O4 O5 O6 O7 O8 O9 P0 P1 P2 P3 P4 P5 P6 P7 P8 P9 Q0 Q1\nQ2 Q3 Q4 Q5 Q6 Q7 Q8 Q9 R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 S0 S1 S2 S3 S4 S5 S6 S7 S8\nS9 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 U0 U1 U2 U3 U4 U5 U6 U7 U8 U9 V0 V1 V2 V3 V4 V5\nV6 V7 V8 V9 W0 W1 W2 W3 W4 W5 W6 W7 W8 W9 X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 Y0 Y1 Y2\nY3 Y4 Y5 Y6 Y7 Y8 Y9 Z0 Z1 Z2 Z3 Z4 Z5 Z6 Z7 Z8 Z9\n</code></pre> <p>Hey.. that saves you writing 260 strings!</p> <p>Brace expansions can be nested, but too much of it usually makes you losing overview a bit ;-)</p> <p>Here's a sample to generate the alphabet, first the uppercase letters, then the lowercase ones:</p> <pre><code>$ echo {{A..Z},{a..z}}\nA B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#common-use-and-examples","title":"Common use and examples","text":"","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#massdownload-from-the-web","title":"Massdownload from the Web","text":"<p>In this example, <code>wget</code> is used to download documentation that is split over several numbered webpages.</p> <p><code>wget</code> won't see your braces. It will see 6 different URLs to download.</p> <pre><code>wget http://docs.example.com/documentation/slides_part{1,2,3,4,5,6}.html\n</code></pre> <p>Of course it's possible, and even easier, to do that with a sequence:</p> <pre><code>wget http://docs.example.com/documentation/slides_part{1..6}.html\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#generate-a-subdirectory-structure","title":"Generate a subdirectory structure","text":"<p>Your life is hard? Let's ease it a bit - that's what shells are here for.</p> <pre><code>mkdir /home/bash/test/{foo,bar,baz,cat,dog}\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#generate-numbers-with-a-prefix-001-002","title":"Generate numbers with a prefix 001 002 ...","text":"<ul> <li> <p>Using a prefix:</p> <p>for i in 0{1..9} 10; do printf \"%s\\n\" \"$i\";done</p> </li> </ul> <p>If you need to create words with the number embedded, you can use nested brace:</p> <pre><code>printf \"%s\\n\" img{00{1..9},0{10..99},{100..999}}.png\n</code></pre> <ul> <li> <p>Formatting the numbers with printf:</p> <p>echo $(printf \"img%02d.png \" {1..99})</p> </li> </ul> <p>See the text below for a new Bash 4 method.</p>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#repeating-arguments-or-words","title":"Repeating arguments or words","text":"<pre><code>somecommand -v -v -v -v -v\n</code></pre> <p>Can be written as</p> <pre><code>somecommand -v{,,,,}\n</code></pre> <p>...which is a kind of a hack, but hey, it works.</p> <p>More fun</p> <p>The most optimal possible brace expansion to expand n arguments of course consists of n's prime factors. We can use the \"factor\" program bundled with GNU coreutils to emit a brace expansion that will expand any number of arguments.</p> <pre><code>function braceify {\n [[ $1 == +([[:digit:]]) ]] || return\n typeset -a a\n read -ra a &lt; &lt;(factor \"$1\")\n eval \"echo $(printf '{$(printf ,%%.s {1..%s})}' \"${a[@]:1}\")\"\n}\n\nprintf 'eval printf \"$arg\"%s' \"$(braceify 1000000)\"\n</code></pre> <p>\"Braceify\" generates the expansion code itself. In this example we inject that output into a template which displays the most terse brace expansion code that would expand <code>\"$arg\"</code> 1,000,000 times if evaluated. In this case, the output is:</p> <pre><code>eval printf \"$arg\"{,,}{,,}{,,}{,,}{,,}{,,}{,,,,,}{,,,,,}{,,,,,}{,,,,,}{,,,,,}{,,,,,}\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#new-in-bash-40","title":"New in Bash 4.0","text":"","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#zero-padded-number-expansion","title":"Zero padded number expansion","text":"<p>Prefix either of the numbers in a numeric range with <code>0</code> to pad the expanded numbers with the correct amount of zeros:</p> <pre><code>$ echo {0001..5}\n0001 0002 0003 0004 0005\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#increment","title":"Increment","text":"<p>It is now possible to specify an increment using ranges:</p> <pre><code>{&lt;START&gt;..&lt;END&gt;..&lt;INCR&gt;}\n</code></pre> <p><code>&lt;INCR&gt;</code> is numeric, you can use a negative integer but the correct sign is deduced from the order of <code>&lt;START&gt;</code> and <code>&lt;END&gt;</code> anyways.</p> <pre><code>$ echo {1..10..2}\n1 3 5 7 9\n$ echo {10..1..2}\n10 8 6 4 2\n</code></pre> <p>Interesting feature: The increment specification also works for letter-ranges:</p> <pre><code>$ echo {a..z..3}\na d g j m p s v y\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/brace/#see-also","title":"See also","text":"<ul> <li>Introduction to expansion and substitution</li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","list","brace"]},{"location":"syntax/expansion/cmdsubst/","title":"Command substitution","text":"<pre><code>$( &lt;COMMANDS&gt; )\n\n` &lt;COMMANDS&gt; `\n</code></pre> <p>The command substitution expands to the output of commands. These commands are executed in a subshell, and their <code>stdout</code> data is what the substitution syntax expands to.</p> <p>All trailing newlines are removed (below is an example for a workaround).</p> <p>In later steps, if not quoted, the results undergo word splitting and pathname expansion. You have to remember that, because the word splitting will also remove embedded newlines and other <code>IFS</code> characters and break the results up into several words. Also you'll probably get unexpected pathname matches. If you need the literal results, quote the command substitution!</p> <p>The second form <code>`COMMAND`</code> is more or less obsolete for Bash, since it has some trouble with nesting (\"inner\" backticks need to be escaped) and escaping characters. Use <code>$(COMMAND)</code>, it's also POSIX!</p> <p>When you call an explicit subshell <code>(COMMAND)</code> inside the command substitution <code>$()</code>, then take care, this way is wrong:</p> <pre><code>$((COMMAND))\n</code></pre> <p>Why? because it collides with the syntax for arithmetic expansion. You need to separate the command substitution from the inner <code>(COMMAND)</code>:</p> <pre><code>$( (COMMAND) )\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","variable","output","execute","stdout","save","result","return","value"]},{"location":"syntax/expansion/cmdsubst/#specialities","title":"Specialities","text":"<p>When the inner command is only an input redirection, and nothing else, for example</p> <pre><code>$( &lt;FILE )\n# or\n` &lt;FILE `\n</code></pre> <p>then Bash attempts to read the given file and act just if the given command was <code>cat FILE</code>.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","output","execute","stdout","save","result","return","value"]},{"location":"syntax/expansion/cmdsubst/#a-closer-look-at-the-two-forms","title":"A closer look at the two forms","text":"<p>In general you really should only use the form <code>$()</code>, it's escaping-neutral, it's nestable, it's also POSIX. But take a look at the following code snips to decide yourself which form you need under specific circumstances:</p> <p>Nesting</p> <p>Backtick form <code>`...`</code> is not directly nestable. You will have to escape the \"inner\" backticks. Also, the deeper you go, the more escape characters you need. Ugly.</p> <pre><code>echo `echo `ls`` # INCORRECT\necho `echo \\`ls\\`` # CORRECT\necho $(echo $(ls)) # CORRECT\n</code></pre> <p>Parsing</p> <p>All is based on the fact that the backquote-form is simple character substitution, while every <code>$()</code>-construct opens an own, subsequent parsing step. Everything inside <code>$()</code> is interpreted as if written normal on a commandline. No special escaping of nothing is needed:</p> <pre><code>echo \"$(echo \"$(ls)\")\" # nested double-quotes - no problem\n</code></pre> <p>Constructs you should avoid</p> <p>It's not all shiny with <code>$()</code>, at least for my current Bash (<code>3.1.17(1)-release</code>. :!: Update: Fixed since <code>3.2-beta</code> together with a misinterpretion of '))' being recognized as arithmetic expansion by redduck666). This command seems to incorrectly close the substitution step and echo prints \"ls\" and \")\":</p> <pre><code>echo $(\n# some comment ending with a )\nls\n)\n</code></pre> <p>It seems that every closing \")\" confuses this construct. Also a (very uncommon ;-)) construct like:</p> <pre><code>echo $(read VAR; case \"$var\" in foo) blah ;; esac) # spits out some error, when it sees the \";;\"\n\n# fixes it:\necho $(read VAR; case \"$var\" in (foo) blah ;; esac) # will work, but just let it be, please ;-)\n</code></pre> <p>Conclusion:</p> <p>In general, the <code>$()</code> should be the preferred method:</p> <ul> <li>it's clean syntax</li> <li>it's intuitive syntax</li> <li>it's more readable</li> <li>it's nestable</li> <li>its inner parsing is separate</li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","variable","output","execute","stdout","save","result","return","value"]},{"location":"syntax/expansion/cmdsubst/#examples","title":"Examples","text":"<p>To get the date:</p> <pre><code>DATE=\"$(date)\"\n</code></pre> <p>To copy a file and get <code>cp</code> error output:</p> <pre><code>COPY_OUTPUT=\"$(cp file.txt /some/where 2&gt;&amp;1)\"\n</code></pre> <p>Attention: Here, you need to redirect <code>cp</code> <code>STDERR</code> to its <code>STDOUT</code> target, because command substitution only catches <code>STDOUT</code>!</p> <p>Catch stdout and preserve trailing newlines:</p> <pre><code>var=$(echo -n $'\\n'); echo -n \"$var\"; # $var == \"\"\nvar=$(echo -n $'\\n'; echo -n x); var=\"${var%x}\"; echo -n \"$var\" # $var == \"\\n\"\n</code></pre> <p>This adds \"x\" to the output, which prevents the trailing newlines of the previous commands' output from being deleted by <code>$()</code>.</p> <p>By removing this \"x\" later on, we are left with the previous commands' output with its trailing newlines.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","output","execute","stdout","save","result","return","value"]},{"location":"syntax/expansion/cmdsubst/#see-also","title":"See also","text":"<ul> <li>Internal: Introduction to expansion and substitution</li> <li>Internal: Obsolete and deprecated syntax</li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","variable","output","execute","stdout","save","result","return","value"]},{"location":"syntax/expansion/globs/","title":"Pathname expansion (globbing)","text":""},{"location":"syntax/expansion/globs/#general","title":"General","text":"<p>Unlike on other platforms you may have seen, on UNIX\u00ae, the shell is responsible for interpreting and expanding globs (\"filename wildcards\"). A called program will never see the glob itself; it will only see the expanded filenames as its arguments (here, all filenames matching <code>*.log</code>):</p> <pre><code>grep \"changes:\" *.log\n</code></pre> <p>The base syntax for the pathname expansion is the pattern matching syntax. The pattern you describe is matched against all existing filenames and the matching ones are substituted. Since this substitution happens after word splitting, all resulting filenames are literal and treated as separate words, no matter how many spaces or other <code>IFS</code>-characters they contain.</p>"},{"location":"syntax/expansion/globs/#normal-behaviour","title":"Normal behaviour","text":"<ul> <li>with the set command (<code>-f</code>, <code>noglob</code>) you can entirely disable pathname expansion</li> <li>when matching a pathname, the slash-character (<code>/</code>) always needs to be matched explicitly</li> <li>the dot at the beginning of a filename must be matched explicitly (also one following a <code>/</code> in the glob)</li> <li>a glob that doesn't match a filename is unchanged and remains what it is</li> </ul>"},{"location":"syntax/expansion/globs/#customization","title":"Customization","text":"<ul> <li>when the shell option <code>nullglob</code> is set, non-matching globs are removed, rather than preserved</li> <li>when the shell option <code>failglob</code> is set, non-matching globs produce an error message and the current command is not executed</li> <li>when the shell option <code>nocaseglob</code> is set, the match is performed case-insensitive</li> <li>when the shell option <code>dotglob</code> is set, wildcard-characters can match a dot at the beginning of a filename</li> <li>when the shell option <code>dirspell</code> is set, Bash performs spelling corrections when matching directory names</li> <li>when the shell option <code>globstar</code> is set, the glob <code>**</code> will recursively match all files and directories. This glob isn't \"configurable\", i.e. you can't do something like <code>**.c</code> to recursively get all <code>*.c</code> filenames.</li> <li>when the shell option <code>globasciiranges</code> is set, the bracket-range globs (e.g. <code>[A-Z]</code>) use C locale order rather than the configured locale's order (i.e. <code>ABC...abc...</code> instead of e.g. <code>AaBbCc...</code>) - since 4.3-alpha</li> <li>the variable GLOBIGNORE can be set to a colon-separated list of patterns to be removed from the list before it is returned</li> </ul>"},{"location":"syntax/expansion/globs/#nullglob","title":"nullglob","text":"<p>Normally, when no glob specified matches an existing filename, no pathname expansion is performed, and the globs are not removed:</p> <pre><code>$ echo \"Textfiles here:\" *.txt\nTextfiles here: *.txt\n</code></pre> <p>In this example, no files matched the pattern, so the glob was left intact (a literal asterisk, followed by dot-txt).</p> <p>This can be very annoying, for example when you drive a for-loop using the pathname expansion:</p> <pre><code>for filename in *.txt; do\n echo \"=== BEGIN: $filename ===\"\n cat \"$filename\"\n echo \"=== END: $filename ===\"\ndone\n</code></pre> <p>When no file name matches the glob, the loop will not only output stupid text (\"<code>BEGIN: *.txt</code>\"), but also will make the <code>cat</code>-command fail with an error, since no file named <code>*.txt</code> exists.</p> <p>Now, when the shell option <code>nullglob</code> is set, Bash will remove the entire glob from the command line. In case of the for-loop here, not even one iteration will be done. It just won't run.</p> <p>So in our first example:</p> <pre><code>$ shopt -s nullglob\n$ echo \"Textfiles here:\" *.txt\nTextfiles here:\n</code></pre> <p>and the glob is gone.</p>"},{"location":"syntax/expansion/globs/#glob-characters","title":"Glob characters","text":"<ul> <li><code>*</code> - means \\'match any number of characters\\'. \\'/\\' is not matched (and depending on your settings, things like \\'.\\' may or may not be matched, see above)</li> <li><code>?</code> - means \\'match any single character\\'</li> <li><code>[abc]</code> - match any of the characters listed. This syntax also supports ranges, like [0-9]</li> </ul> <p>For example, to match something beginning with either \\'S\\' or \\'K\\' followed by two numbers, followed by at least 3 more characters:</p> <pre><code>[SK][0-9][0-9]???*\n</code></pre>"},{"location":"syntax/expansion/globs/#see-also","title":"See also","text":"<ul> <li>Introduction to expansion and substitution</li> <li>pattern matching syntax</li> <li>the set builtin command</li> <li>the shopt builtin command</li> <li>list of shell options</li> </ul>"},{"location":"syntax/expansion/intro/","title":"Expansions and substitutions","text":"<p>Before executing your commands, Bash checks whether there are any syntax elements in the command line that should be interpreted rather than taken literally. After splitting the command line into tokens (words), Bash scans for these special elements and interprets them, resulting in a changed command line: the elements are said to be expanded to or substituted to new text and maybe new tokens (words).</p> <p>The most simple example of this behaviour is a referenced variable:</p> <pre><code>mystring=\"Hello world\"\necho \"$mystring\"\n</code></pre> <p>The <code>echo</code> program definitely doesn't care about what a shell variable is. It is Bash's job to deal with the variable. Bash expands the string \"<code>$mystring</code>\" to \"<code>Hello world</code>\", so that <code>echo</code> will only see <code>Hello world</code>, not the variable or anything else!</p> <p>After all these expansions and substitutions are done, all quotes that are not meant literally (i.e., the quotes that marked contiguous words, as part of the shell syntax) are removed from the commandline text, so the called program won't see them. This step is called quote-removal.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","filename","macro","wildcard"]},{"location":"syntax/expansion/intro/#overview","title":"Overview","text":"<p>Saw a possible expansion syntax but don't know what it is? Here's a small list.</p> <ul> <li>Parameter expansion (it has its own overview section)<ul> <li><code>$WORD</code></li> <li><code>${STUFF...}</code></li> </ul> </li> <li>Pathname expansion<ul> <li><code>*.txt</code></li> <li><code>page_1?.html</code></li> </ul> </li> <li>Arithmetic expansion<ul> <li><code>$(( EXPRESSION ))</code></li> <li><code>$[ EXPRESSION ]</code></li> </ul> </li> <li>Command substitution<ul> <li><code>$( COMMAND )</code></li> <li><code>` COMMAND `</code></li> </ul> </li> <li>Tilde expansion<ul> <li><code>~</code></li> <li><code>~+</code></li> <li><code>~-</code></li> </ul> </li> <li>Brace expansion<ul> <li><code>{X,Y,Z}</code></li> <li><code>{X..Y}</code></li> <li><code>{X..Y..Z}</code></li> </ul> </li> <li>Process substitution<ul> <li><code>&lt;( COMMAND )</code></li> <li><code>&gt;( COMMAND )</code></li> </ul> </li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","variable","filename","macro","wildcard"]},{"location":"syntax/expansion/intro/#order","title":"Order","text":"<p>Bash performs expansions and substitutions in a defined order. This explains why globbing (pathname expansion), for example, is safe to use on filenames with spaces (because it happens after the final word splitting!).</p> <p>The order is (from first to last):</p> <ul> <li>Brace expansion</li> <li>Tilde expansion</li> <li>The following expansions happen at the same time, in a left-to-right fashion on the commandline (see below)<ul> <li>Parameter expansion</li> <li>Arithmetic expansion</li> <li>Command substitution</li> </ul> </li> <li>Word splitting</li> <li>Pathname expansion</li> </ul> <p>Process substitution is performed simultaneously with parameter expansion, command substitution and arithmetic expansion. It is only performed when the underlying operating system supports it.</p> <p>The 3 steps parameter expansion, arithmetic expansion and command substitution happen at the same time in a left-to-right fashion on nthe commandline. This means</p> <pre><code>i=1\necho $i $((i++)) $i\n</code></pre> <p>will output <code>1 1 2</code> and not <code>1 1 1</code>.</p>","tags":["bash","shell","scripting","expansion","substitution","text","variable","filename","macro","wildcard"]},{"location":"syntax/expansion/proc_subst/","title":"Process substitution","text":"<p>Process substitution is a form of redirection where the input or output of a process (some sequence of commands) appear as a temporary file.</p> <pre><code>&lt;( &lt;LIST&gt; )\n\n&gt;( &lt;LIST&gt; )\n</code></pre> <p>Process substitution is performed simultaneously with parameter expansion, command substitution and arithmetic expansion.</p> <p>The command list <code>&lt;LIST&gt;</code> is executed and its</p> <ul> <li>standard output filedescriptor in the <code>&lt;( ... )</code> form or</li> <li>standard input filedescriptor in the <code>&gt;( ... )</code> form</li> </ul> <p>is connected to a FIFO or a file in <code>/dev/fd/</code>. The filename (where the filedescriptor is connected) is then used as a substitution for the <code>&lt;(...)</code>-construct.</p> <p>That, for example, allows to give data to a command that can't be reached by pipelining (that doesn't expect its data from <code>stdin</code> but from a file).</p>","tags":["bash","shell","scripting","expansion","substitution","text","stdin","stdout","save","capture"]},{"location":"syntax/expansion/proc_subst/#scope","title":"Scope","text":"<p>Note</p> <p>According to multiple comments and sources, the scope of process substitution file descriptors is not stable, guaranteed, or specified by bash. Newer versions of bash (5.0+) seem to have shorter scope, and substitutions scope seems to be shorter than function scope. See stackexchange and stackoverflow; the latter discussion contains a script that can test the scoping behavior case-by-case</p> <p>If a process substitution is expanded as an argument to a function, expanded to an environment variable during calling of a function, or expanded to any assignment within a function, the process substitution will be \"held open\" for use by any command within the function or its callees, until the function in which it was set returns. If the same variable is set again within a callee, unless the new variable is local, the previous process substitution is closed and will be unavailable to the caller when the callee returns.</p> <p>In essence, process substitutions expanded to variables within functions remain open until the function in which the process substitution occured returns - even when assigned to locals that were set by a function's caller. Dynamic scope doesn't protect them from closing.</p>","tags":["bash","shell","scripting","expansion","substitution","text","stdin","stdout","save","capture"]},{"location":"syntax/expansion/proc_subst/#examples","title":"Examples","text":"<p>This code is useless, but it demonstrates how it works:</p> <pre><code>$ echo &lt;(ls)\n/dev/fd/63\n</code></pre> <p>The output of the <code>ls</code>-program can then be accessed by reading the file <code>/dev/fd/63</code>.</p> <p>Consider the following:</p> <pre><code>diff &lt;(ls \"$first_directory\") &lt;(ls \"$second_directory\")\n</code></pre> <p>This will compare the contents of each directory. In this command, each process is substituted for a file, and diff doesn't see &lt;(bla), it sees two files, so the effective command is something like</p> <pre><code>diff /dev/fd/63 /dev/fd/64\n</code></pre> <p>where those files are written to and destroyed automatically.</p>","tags":["bash","shell","scripting","expansion","substitution","text","stdin","stdout","save","capture"]},{"location":"syntax/expansion/proc_subst/#avoiding-subshells","title":"Avoiding subshells","text":"<p>See Also</p> <p>See Also: BashFAQ/024 -- I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?</p> <p>One of the most common uses for process substitutions is to avoid the final subshell that results from executing a pipeline. The following is a wrong piece of code to count all files in <code>/etc</code> is:</p> <pre><code>counter=0\n\nfind /etc -print0 | while IFS= read -rd '' _; do\n ((counter++))\ndone\n\necho \"$counter files\" # prints \"0 files\"\n</code></pre> <p>Due to the pipe, the <code>while read; do ... done</code> part is executed in a subshell (in Bash, by default), which means <code>counter</code> is only incremented within the subshell. When the pipeline finishes, the subshell is terminated, and the <code>counter</code> visible to <code>echo</code> is still at \"0\"!</p> <p>Process substitution helps us avoid the pipe operator (the reason for the subshell):</p> <pre><code>counter=0\n\nwhile IFS= read -rN1 _; do\n ((counter++))\ndone &lt; &lt;(find /etc -printf ' ')\n\necho \"$counter files\"\n</code></pre> <p>This is the normal input file redirection <code>&lt; FILE</code>, just that the <code>FILE</code> in this case is the result of process substitution. It's important to note that the space is required in order to disambiguate the syntax from here documents.</p> <pre><code>: &lt; &lt;(COMMAND) # Good.\n: &lt;&lt;(...) # Wrong. Will be parsed as a heredoc. Bash fails when it comes across the unquoted metacharacter ''(''\n: &gt;&lt;(...) # Technically valid but pointless syntax. Bash opens the pipe for writing, while the commands within the process substitution have their stdout connected to the pipe.\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","text","stdin","stdout","save","capture"]},{"location":"syntax/expansion/proc_subst/#process-substitution-assigned-to-a-parameter","title":"Process substitution assigned to a parameter","text":"<p>This example demonstrates how process substitutions can be made to resemble \"passable\" objects. This results in converting the output of <code>f</code>'s argument to uppercase.</p> <pre><code>f() {\n cat \"$1\" &gt;\"$x\"\n}\n\nx=&gt;(tr '[:lower:]' '[:upper:]') f &lt;(echo 'hi there')\n</code></pre> <p>See the above section on #scope</p>","tags":["bash","shell","scripting","expansion","substitution","text","stdin","stdout","save","capture"]},{"location":"syntax/expansion/proc_subst/#bugs-and-portability-considerations","title":"Bugs and Portability Considerations","text":"<ul> <li>Process substitution is not specified by POSIX.</li> <li>Process substitution is disabled completely in Bash POSIX mode.</li> <li>Process substitution is implemented by Bash, Zsh, Ksh{88,93}, but not (yet) pdksh derivatives (mksh). Coprocesses may be used instead.</li> <li>Process substitution is supported only on systems that support either named pipes (FIFO - a special file) or the <code>/dev/fd/*</code> method for accessing open files. If the system doesn't support <code>/dev/fd/*</code>, Bash falls back to creating named pipes. Note that not all shells that support process substitution have that fallback.</li> <li>Bash evaluates process substitutions within array indices, but not other arithmetic contexts. Ksh and Zsh do not. (Possible Bug)</li> </ul> <pre><code># print \"moo\"\ndev=fd=1 _[1&lt;(echo moo &gt;&amp;2)]=\n# fork bomb\n${dev[${dev='dev[1&gt;(${dev[dev]})]'}]}\n</code></pre> <ul> <li>Issues with wait, race conditions, etc: https://groups.google.com/forum/?fromgroups=#!topic/comp.unix.shell/GqLNzUA4ulA</li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","stdin","stdout","save","capture"]},{"location":"syntax/expansion/proc_subst/#see-also","title":"See also","text":"<ul> <li>Internal: Introduction to expansion and substitution</li> <li>Internal: Bash in the process tree (subshells)</li> <li>Internal: Redirection</li> </ul>","tags":["bash","shell","scripting","expansion","substitution","text","stdin","stdout","save","capture"]},{"location":"syntax/expansion/tilde/","title":"Tilde expansion","text":"<pre><code>~\n~/...\n\n~NAME\n~NAME/...\n\n~+\n~+/...\n\n~-\n~-/...\n</code></pre> <p>The tilde expansion is used to expand to several specific pathnames:</p> <ul> <li>home directories</li> <li>current working directory</li> <li>previous working directory</li> </ul> <p>Tilde expansion is only performed, when the tilde-construct is at the beginning of a word, or a separate word.</p> <p>If there's nothing to expand, i.e., in case of a wrong username or any other error condition, the tilde construct is not replaced, it stays what it is.</p> <p>Tilde expansion is also performed everytime a variable is assigned:</p> <ul> <li>after the first <code>=</code>: <code>TARGET=~moonman/share</code></li> <li>after every <code>:</code> (colon) in the assigned value: <code>TARGET=file:~moonman/share</code></li> </ul> <p>Note</p> <p>As of now (Bash 4.3-alpha) the following constructs also works, though it's not a variable assignment:</p> <pre><code>echo foo=~\necho foo=:~\n</code></pre> <p>I don't know yet, if this is a bug or intended.</p> <p>This way you can correctly use the tilde expansion in your PATH:</p> <pre><code>PATH=~/mybins:~peter/mybins:$PATH\n</code></pre> <p>Spaces in the referenced pathes? A construct like...</p> <pre><code>~/\"my directory\"\n</code></pre> <p>...is perfectly valid and works!</p>","tags":["bash","shell","scripting","expansion","substitution","tilde","home","homedir","shortcut"]},{"location":"syntax/expansion/tilde/#home-directory","title":"Home directory","text":"<pre><code>~\n~&lt;NAME&gt;\n</code></pre> <p>This form expands to the home-directory of the current user (<code>~</code>) or the home directory of the given user (<code>~&lt;NAME&gt;</code>).</p> <p>If the given user doesn't exist (or if his home directory isn't determinable, for some reason), it doesn't expand to something else, it stays what it is. The requested home directory is found by asking the operating system for the associated home directory for <code>&lt;NAME&gt;</code>.</p> <p>To find the home directory of the current user (<code>~</code>), Bash has a precedence:</p> <ul> <li>expand to the value of HOME if it's defined</li> <li>expand to the home directory of the user executing the shell (operating system)</li> </ul> <p>That means, the variable <code>HOME</code> can override the \"real\" home directory, at least regarding tilde expansion.</p>","tags":["bash","shell","scripting","expansion","substitution","tilde","home","homedir","shortcut"]},{"location":"syntax/expansion/tilde/#current-working-directory","title":"Current working directory","text":"<pre><code>~+\n</code></pre> <p>This expands to the value of the PWD variable, which holds the currect working directory:</p> <pre><code>echo \"CWD is $PWD\"\n</code></pre> <p>is equivalent to (note it must be a separate word!):</p> <pre><code>echo \"CWD is\" ~+\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","tilde","home","homedir","shortcut"]},{"location":"syntax/expansion/tilde/#previous-working-directory","title":"Previous working directory","text":"<pre><code>~-\n</code></pre> <p>This expands to the value of the OLDPWD variable, which holds the previous working directory (the one before the last <code>cd</code>). If <code>OLDPWD</code> is unset (never changed the directory), it is not expanded.</p> <pre><code>$ pwd\n/home/bash\n$ cd /etc\n$ echo ~-\n/home/bash\n</code></pre>","tags":["bash","shell","scripting","expansion","substitution","tilde","home","homedir","shortcut"]},{"location":"syntax/expansion/tilde/#see-also","title":"See also","text":"<ul> <li>Internal: Introduction to expansion and substitution</li> </ul>","tags":["bash","shell","scripting","expansion","substitution","tilde","home","homedir","shortcut"]},{"location":"syntax/expansion/wordsplit/","title":"Word splitting","text":"<p>FIXME</p> <p>to be continued!</p> <p>Word splitting occurs once any of the following expansions are done (and only then!)</p> <ul> <li>Parameter expansion</li> <li>Command substitution</li> <li>Arithmetic expansion</li> </ul> <p>Bash will scan the results of these expansions for special <code>IFS</code> characters that mark word boundaries. This is only done on results that are not double-quoted!</p>"},{"location":"syntax/expansion/wordsplit/#internal-field-separator-ifs","title":"Internal Field Separator IFS","text":"<p>The <code>IFS</code> variable holds the characters that Bash sees as word boundaries in this step. The default contains the characters</p> <ul> <li>&lt;space&gt;</li> <li>&lt;tab&gt;</li> <li>&lt;newline&gt;</li> </ul> <p>These characters are also assumed when IFS is unset. When <code>IFS</code> is empty (nullstring), no word splitting is performed at all.</p>"},{"location":"syntax/expansion/wordsplit/#behaviour","title":"Behaviour","text":"<p>The results of the expansions mentioned above are scanned for <code>IFS</code>-characters. If one or more (in a sequence) of them is found, the expansion result is split at these positions into multiple words.</p> <p>This doesn't happen when the expansion results were double-quoted.</p> <p>When a null-string (e.g., something that before expanded to &gt;&gt;nothing&lt;&lt;) is found, it is removed, unless it is quoted (<code>''</code> or <code>\"\"</code>).</p> <p>Again note: Without any expansion beforehand, Bash won't perform word splitting! In this case, the initial token parsing is solely responsible.</p>"},{"location":"syntax/expansion/wordsplit/#see-also","title":"See also","text":"<ul> <li>Introduction to expansion and substitution</li> <li>Quoting and escaping</li> <li>WordSplitting, IFS, and DontReadLinesWithFor - Greg's wiki</li> </ul>"},{"location":"syntax/grammar/parser_exec/","title":"Parser exec","text":"<p>FIXME</p> <p>work in progress...</p>","tags":["bash","shell","scripting","syntax","language","behaviour","executing","execution"]},{"location":"syntax/grammar/parser_exec/#parsing-and-execution","title":"Parsing and execution","text":"<p>Nearly everything in Bash grammar can be broken down to a \"simple command\". The only thing Bash has to expand, evaluate and execute is the simple command.</p>","tags":["bash","shell","scripting","syntax","language","behaviour","executing","execution"]},{"location":"syntax/grammar/parser_exec/#simple-command-expansion","title":"Simple command expansion","text":"<p>info</p> <ul> <li>http://lists.gnu.org/archive/html/bug-bash/2013-01/msg00040.html</li> <li>http://lists.research.att.com/pipermail/ast-developers/2013q2/002456.html</li> </ul> <p>This step happens after the initial command line splitting.</p> <p>The expansion of a simple command is done in four steps (interpreting the simple command from left to right):</p> <ol> <li>The words the parser has marked as variable assignments and redirections are saved for later processing.<ul> <li>variable assignments precede the command name and have the form <code>WORD=WORD</code></li> <li>redirections can appear anywhere in the simple command</li> </ul> </li> <li>The rest of the words are expanded. If any words remain after expansion, the first word is taken to be the name of the command and the remaining words are the arguments.</li> <li>Redirections are performed.</li> <li>The text after the <code>=</code> in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal before being assigned to the variable.</li> </ol> <p>If no command name results after expansion:</p> <ul> <li>The variable assignments affect the current shell environment.<ul> <li>This is what happens when you enter only a variable assignment at the command prompt.</li> <li>Assignment to readonly variables causes an error and the command exits non-zero.</li> </ul> </li> <li>Redirections are performed, but do not affect the current shell environment.<ul> <li>that means, a <code>&gt; FILE</code> without any command will be performed: the <code>FILE</code> will be created!</li> </ul> </li> <li>The command exits<ul> <li>with an exit code indicating the redirection error, if any</li> <li>with the exit code of the last command-substitution parsed, if any</li> <li>with exit code 0 (zero) if no redirection error happened and no command substitution was done</li> </ul> </li> </ul> <p>Otherwise, if a command name results:</p> <ul> <li>The variables saved and parsed are added to the environment of the executed command (and thus do not affect the current environment)<ul> <li>Assignment to readonly variables causes an error and the command exits with a non-zero error code.</li> <li>Assignment errors in non-POSIX modes cause the enclosing commands (e.g. loops) to completely terminate</li> <li>Assignment errors in (non-interactive) POSIX mode cause the entire script to terminate</li> </ul> </li> </ul> <p>The behavior regarding the variable assignment errors can be tested:</p> <p>This one exits the script completely</p> <pre><code>#!/bin/sh\n# This shell runs in POSIX mode!\n\necho PRE\n\n# The following is an assignment error, since there is no digit '9'\n# for a base eight number!\nfoo=$((8#9))\n\necho POST\n</code></pre> <p>This one terminates only the enclosing compound command (the <code>{ ...; }</code>):</p> <pre><code>#!/bin/bash\n# This shell runs in native Bash-mode!\n\necho PRE\n\n# The following is an assignment error!\n# The \"echo TEST\" won't be executed, since the { ...; } is terminated\n{ foo=$((8#9)); echo TEST; }\n\necho POST\n</code></pre>","tags":["bash","shell","scripting","syntax","language","behaviour","executing","execution"]},{"location":"syntax/grammar/parser_exec/#simple-command-execution","title":"Simple command execution","text":"<p>If a parsed simple command contains no slashes, the shell attempts to locate and execute it:</p> <ul> <li>shell functions</li> <li>shell builtin commands</li> <li>check own hash table</li> <li>search along <code>PATH</code></li> </ul> <p>As of Bash Version 4, when a command search fails, the shell executes a shell function named <code>command_not_found_handle()</code> using the failed command as arguments. This can be used to provide user friendly messages or install software packages etc. Since this function runs in a separate execution environment, you can't really influence the main shell with it (changing directory, setting variables).</p> <p>FIXME</p> <p>to be continued</p>","tags":["bash","shell","scripting","syntax","language","behaviour","executing","execution"]},{"location":"syntax/grammar/parser_exec/#see-also","title":"See also","text":"<ul> <li>Internal: Redirection</li> <li>Internal: Introduction to expansions and substitutions</li> </ul>","tags":["bash","shell","scripting","syntax","language","behaviour","executing","execution"]},{"location":"syntax/keywords/coproc/","title":"The coproc keyword","text":""},{"location":"syntax/keywords/coproc/#synopsis","title":"Synopsis","text":"<pre><code> coproc [NAME] command [redirections]\n</code></pre>"},{"location":"syntax/keywords/coproc/#description","title":"Description","text":"<p>Bash 4.0 introduced coprocesses, a feature certainly familiar to ksh users. The <code>coproc</code> keyword starts a command as a background job, setting up pipes connected to both its stdin and stdout so that you can interact with it bidirectionally. Optionally, the co-process can have a name <code>NAME</code>. If <code>NAME</code> is given, the command that follows must be a compound command. If no <code>NAME</code> is given, then the command can be either simple or compound.</p> <p>The process ID of the shell spawned to execute the coprocess is available through the value of the variable named by <code>NAME</code> followed by a <code>_PID</code> suffix. For example, the variable name used to store the PID of a coproc started with no <code>NAME</code> given would be <code>COPROC_PID</code> (because <code>COPROC</code> is the default <code>NAME</code>). wait may be used to wait for the coprocess to terminate. Additionally, coprocesses may be manipulated through their <code>jobspec</code>.</p>"},{"location":"syntax/keywords/coproc/#return-status","title":"Return status","text":"<p>The return status of a coprocess is the exit status of its command.</p>"},{"location":"syntax/keywords/coproc/#redirections","title":"Redirections","text":"<p>The optional redirections are applied after the pipes have been set up. Some examples:</p> <pre><code># redirecting stderr in the pipe\n$ coproc { ls thisfiledoesntexist; read; } 2&gt;&amp;1\n[2] 23084\n$ IFS= read -ru ${COPROC[0]} x; printf '%s\\n' \"$x\"\nls: cannot access thisfiledoesntexist: No such file or directory\n</code></pre> <pre><code>#let the output of the coprocess go to stdout\n$ { coproc mycoproc { awk '{print \"foo\" $0;fflush()}'; } &gt;&amp;3; } 3&gt;&amp;1\n[2] 23092\n$ echo bar &gt;&amp;${mycoproc[1]}\n$ foobar\n</code></pre> <p>Here we need to save the previous file descriptor of stdout, because by the time we redirect the fds of the coprocess, stdout has already been redirected to the pipe.</p>"},{"location":"syntax/keywords/coproc/#pitfalls","title":"Pitfalls","text":""},{"location":"syntax/keywords/coproc/#avoid-the-final-pipeline-subshell","title":"Avoid the final pipeline subshell","text":"<p>The traditional Ksh workaround to avoid the subshell when doing <code>command | while read</code> is to use a coprocess. Unfortunately, Bash's behavior differs.</p> <p>In Ksh you would do:</p> <pre><code># ksh93 or mksh/pdksh derivatives\nls |&amp; # start a coprocess\nwhile IFS= read -rp file; do print -r -- \"$file\"; done # read its output\n</code></pre> <p>In bash:</p> <pre><code>#DOESN'T WORK\n$ coproc ls\n[1] 23232\n$ while IFS= read -ru ${COPROC[0]} line; do printf '%s\\n' \"$line\"; done\nbash: read: line: invalid file descriptor specification\n[1]+ Done coproc COPROC ls\n</code></pre> <p>By the time we start reading from the output of the coprocess, the file descriptor has been closed.</p> <p>See this FAQ entry on Greg's wiki for other pipeline subshell workarounds.</p>"},{"location":"syntax/keywords/coproc/#buffering","title":"Buffering","text":"<p>In the first example, we GNU awk's <code>fflush()</code> command. As always, when you use pipes the I/O operations are buffered. Let's see what happens with <code>sed</code>:</p> <pre><code>$ coproc sed s/^/foo/\n[1] 22981\n$ echo bar &gt;&amp;${COPROC[1]}\n$ read -t 3 -ru ${COPROC[0]} _; (( $? &gt; 127 )) &amp;&amp; echo \"nothing read\"\nnothing read\n</code></pre> <p>Even though this example is the same as the first <code>awk</code> example, the <code>read</code> doesn't return because the output is waiting in a buffer.</p> <p>See this faq entry on Greg's wiki for some workarounds and more information on buffering issues.</p>"},{"location":"syntax/keywords/coproc/#background-processes","title":"background processes","text":"<p>A coprocess' file descriptors are accessible only to the process from which the <code>coproc</code> was started. They are not inherited by subshells.</p> <p>Here is a not-so-meaningful illustration. Suppose we want to continuously read the output of a coprocess and <code>echo</code> the result:</p> <pre><code>#NOT WORKING\n$ coproc awk '{print \"foo\" $0;fflush()}'\n[2] 23100\n$ while IFS= read -ru ${COPROC[0]} x; do printf '%s\\n' \"$x\"; done &amp;\n[3] 23104\nbash: line 243: read: 61: invalid file descriptor: Bad file descriptor\n</code></pre> <p>This fails because the file descriptors created by the parent are not available to the subshell created by &amp;.</p> <p>A possible workaround:</p> <pre><code>#WARNING: for illustration purpose ONLY\n# this is not the way to make the coprocess print its output\n# to stdout, see the redirections above.\n$ coproc awk '{print \"foo\" $0;fflush()}'\n[2] 23109\n$ exec 3&lt;&amp;${COPROC[0]}\n$ while IFS= read -ru 3 x; do printf '%s\\n' \"$x\"; done &amp;\n[3] 23110\n$ echo bar &gt;&amp;${COPROC[1]}\n$ foobar\n</code></pre> <p>Here, fd 3 is inherited.</p>"},{"location":"syntax/keywords/coproc/#examples","title":"Examples","text":""},{"location":"syntax/keywords/coproc/#anonymous-coprocess","title":"Anonymous Coprocess","text":"<p>Unlike ksh, Bash doesn't have true anonymous coprocesses. Instead, Bash assigns FDs to a default array named <code>COPROC</code> if no <code>NAME</code> is supplied. Here's an example:</p> <pre><code>$ coproc awk '{print \"foo\" $0;fflush()}'\n[1] 22978\n</code></pre> <p>This command starts in the background, and <code>coproc</code> returns immediately. Two new file descriptors are now available via the <code>COPROC</code> array. We can send data to our command:</p> <pre><code>$ echo bar &gt;&amp;${COPROC[1]}\n</code></pre> <p>And then read its output:</p> <pre><code>$ IFS= read -ru ${COPROC[0]} x; printf '%s\\n' \"$x\"\nfoobar\n</code></pre> <p>When we don't need our command anymore, we can kill it via its pid:</p> <pre><code>$ kill $COPROC_PID\n$\n[1]+ Terminated coproc COPROC awk '{print \"foo\" $0;fflush()}'\n</code></pre>"},{"location":"syntax/keywords/coproc/#named-coprocess","title":"Named Coprocess","text":"<p>Using a named coprocess is simple. We just need a compound command (like when defining a function), and the resulting FDs will be assigned to the indexed array <code>NAME</code> we supply instead.</p> <pre><code>$ coproc mycoproc { awk '{print \"foo\" $0;fflush()}' ;}\n[1] 23058\n$ echo bar &gt;&amp;${mycoproc[1]}\n$ IFS= read -ru ${mycoproc[0]} x; printf '%s\\n' \"$x\"\nfoobar\n$ kill $mycoproc_PID\n$\n[1]+ Terminated coproc mycoproc { awk '{print \"foo\" $0;fflush()}'; }\n</code></pre>"},{"location":"syntax/keywords/coproc/#redirecting-the-output-of-a-script-to-a-file-and-to-the-screen","title":"Redirecting the output of a script to a file and to the screen","text":"<pre><code>#!/bin/bash\n# we start tee in the background\n# redirecting its output to the stdout of the script\n{ coproc tee { tee logfile ;} &gt;&amp;3 ;} 3&gt;&amp;1\n# we redirect stding and stdout of the script to our coprocess\nexec &gt;&amp;${tee[1]} 2&gt;&amp;1\n</code></pre>"},{"location":"syntax/keywords/coproc/#portability-considerations","title":"Portability considerations","text":"<ul> <li>The <code>coproc</code> keyword is not specified by POSIX(R)</li> <li>The <code>coproc</code> keyword appeared in Bash version 4.0-alpha</li> <li>The <code>-p</code> option to Bash's <code>print</code> loadable is a NOOP and not connected to Bash coprocesses in any way. It is only recognized as an option for ksh compatibility, and has no effect.</li> <li>The <code>-p</code> option to Bash's <code>read</code> builtin conflicts with that of all kshes and zsh. The equivalent in those shells is to add a <code>\\?prompt</code> suffix to the first variable name argument to <code>read</code>. i.e., if the first variable name given contains a <code>?</code> character, the remainder of the argument is used as the prompt string. Since this feature is pointless and redundant, I suggest not using it in either shell. Simply precede the <code>read</code> command with a <code>printf %s prompt &gt;&amp;2</code>.</li> </ul>"},{"location":"syntax/keywords/coproc/#other-shells","title":"Other shells","text":"<p>ksh93, mksh, zsh, and Bash all support something called \"coprocesses\" which all do approximately the same thing. ksh93 and mksh have virtually identical syntax and semantics for coprocs. A list operator: <code>|&amp;</code> is added to the language which runs the preceding pipeline as a coprocess (This is another reason not to use the special <code>|&amp;</code> pipe operator in Bash -- its syntax is conflicting). The <code>-p</code> option to the <code>read</code> and <code>print</code> builtins can then be used to read and write to the pipe of the coprocess (whose FD isn't yet known). Special redirects are added to move the last spawned coprocess to a different FD: <code>&lt;&amp;p</code> and <code>&gt;&amp;p</code>, at which point it can be accessed at the new FD using ordinary redirection, and another coprocess may then be started, again using <code>|&amp;</code>.</p> <p>zsh coprocesses are very similar to ksh except in the way they are started. zsh adds the shell reserved word <code>coproc</code> to the pipeline syntax (similar to the way Bash's <code>time</code> keyword works), so that the pipeline that follows is started as a coproc. The coproc's input and output FDs can then be accessed and moved using the same <code>read</code>/<code>print</code> <code>-p</code> and redirects used by the ksh shells.</p> <p>It is unfortunate that Bash chose to go against existing practice in their coproc implementation, especially considering it was the last of the major shells to incorporate this feature. However, Bash's method accomplishes the same without requiring nearly as much additional syntax. The <code>coproc</code> keyword is easy enough to wrap in a function such that it takes Bash code as an ordinary argument and/or stdin like <code>eval</code>. Coprocess functionality in other shells can be similarly wrapped to create a <code>COPROC</code> array automatically.</p>"},{"location":"syntax/keywords/coproc/#only-one-coprocess-at-a-time","title":"Only one coprocess at a time","text":"<p>The title says it all, complain to the bug-bash mailing list if you want more. See http://lists.gnu.org/archive/html/bug-bash/2011-04/msg00056.html for more details</p> <p>The ability to use multiple coprocesses in Bash is considered \"experimental\". Bash will throw an error if you attempt to start more than one. This may be overridden at compile-time with the <code>MULTIPLE_COPROCS</code> option. However, at this time there are still issues -- see the above mailing list discussion.</p>"},{"location":"syntax/keywords/coproc/#see-also","title":"See also","text":"<ul> <li>Anthony Thyssen's Coprocess Hints - excellent summary of everything around the topic</li> </ul>"},{"location":"tags/","title":"Tags","text":"<p>Following is a list of all existing tags:</p>"},{"location":"tags/#c","title":"C","text":"<ul> <li>Arithmetic expressions</li> </ul>"},{"location":"tags/#posix","title":"POSIX","text":"<ul> <li>pax - the POSIX archiver</li> <li>Bash's behaviour</li> <li>Portability talk</li> </ul>"},{"location":"tags/#ansi","title":"ansi","text":"<ul> <li>Terminal codes (ANSI/VT100) introduction</li> </ul>"},{"location":"tags/#archive","title":"archive","text":"<ul> <li>pax - the POSIX archiver</li> </ul>"},{"location":"tags/#arguments","title":"arguments","text":"<ul> <li>Editing files via scripts with ed</li> <li>Small getopts tutorial</li> <li>Handling positional parameters</li> <li>Generate code with own arguments properly quoted</li> </ul>"},{"location":"tags/#arithmetic","title":"arithmetic","text":"<ul> <li>Calculating with dc</li> <li>Arithmetic expressions</li> </ul>"},{"location":"tags/#array","title":"array","text":"<ul> <li>Parameter expansion</li> </ul>"},{"location":"tags/#arrays","title":"arrays","text":"<ul> <li>Parameter expansion</li> </ul>"},{"location":"tags/#awk","title":"awk","text":"<ul> <li>Using awk to deal with CSV that uses quoted/unquoted delimiters</li> </ul>"},{"location":"tags/#backslash","title":"backslash","text":"<ul> <li>Quotes and escaping</li> </ul>"},{"location":"tags/#bash","title":"bash","text":"<ul> <li>Start</li> <li>Calculating with dc</li> <li>Collapsing Functions</li> <li>Config files for your script</li> <li>Editing files via scripts with ed</li> <li>Small getopts tutorial</li> <li>Lock your script (against parallel execution)</li> <li>pax - the POSIX archiver</li> <li>Illustrated Redirection Tutorial</li> <li>List of shell options</li> <li>Bash's behaviour</li> <li>The basics of shell scripting</li> <li>Debugging a script</li> <li>Beginner Mistakes</li> <li>Portability talk</li> <li>Obsolete and deprecated syntax</li> <li>Handling positional parameters</li> <li>Bash and the process tree</li> <li>Terminal codes (ANSI/VT100) introduction</li> <li>Small code snipplets</li> <li>Arithmetic expressions</li> <li>Basic grammar rules of Bash</li> <li>Patterns and pattern matching</li> <li>Parameter expansion</li> <li>Quotes and escaping</li> <li>Words...</li> <li>Brace expansion</li> <li>Command substitution</li> <li>Expansions and substitutions</li> <li>Process substitution</li> <li>Tilde expansion</li> <li>Parser exec</li> </ul>"},{"location":"tags/#basics","title":"basics","text":"<ul> <li>The basics of shell scripting</li> </ul>"},{"location":"tags/#beginners","title":"beginners","text":"<ul> <li>Beginner Mistakes</li> </ul>"},{"location":"tags/#behaviour","title":"behaviour","text":"<ul> <li>List of shell options</li> <li>Parser exec</li> </ul>"},{"location":"tags/#brace","title":"brace","text":"<ul> <li>Brace expansion</li> </ul>"},{"location":"tags/#bug","title":"bug","text":"<ul> <li>Debugging a script</li> </ul>"},{"location":"tags/#calculate","title":"calculate","text":"<ul> <li>Calculating with dc</li> </ul>"},{"location":"tags/#calculation","title":"calculation","text":"<ul> <li>Arithmetic expressions</li> </ul>"},{"location":"tags/#capture","title":"capture","text":"<ul> <li>Process substitution</li> </ul>"},{"location":"tags/#change","title":"change","text":"<ul> <li>Parameter expansion</li> </ul>"},{"location":"tags/#check","title":"check","text":"<ul> <li>Parameter expansion</li> </ul>"},{"location":"tags/#code","title":"code","text":"<ul> <li>Small code snipplets</li> </ul>"},{"location":"tags/#collapse","title":"collapse","text":"<ul> <li>Collapsing Functions</li> </ul>"},{"location":"tags/#colors","title":"colors","text":"<ul> <li>Terminal codes (ANSI/VT100) introduction</li> </ul>"},{"location":"tags/#config","title":"config","text":"<ul> <li>Config files for your script</li> </ul>"},{"location":"tags/#configuration","title":"configuration","text":"<ul> <li>Config files for your script</li> </ul>"},{"location":"tags/#control","title":"control","text":"<ul> <li>Terminal codes (ANSI/VT100) introduction</li> </ul>"},{"location":"tags/#csv","title":"csv","text":"<ul> <li>Using awk to deal with CSV that uses quoted/unquoted delimiters</li> </ul>"},{"location":"tags/#cursor","title":"cursor","text":"<ul> <li>Terminal codes (ANSI/VT100) introduction</li> </ul>"},{"location":"tags/#debug","title":"debug","text":"<ul> <li>Debugging a script</li> </ul>"},{"location":"tags/#debugging","title":"debugging","text":"<ul> <li>Debugging a script</li> </ul>"},{"location":"tags/#defined","title":"defined","text":"<ul> <li>Parameter expansion</li> </ul>"},{"location":"tags/#deprecated","title":"deprecated","text":"<ul> <li>Obsolete and deprecated syntax</li> </ul>"},{"location":"tags/#descriptor","title":"descriptor","text":"<ul> <li>Illustrated Redirection Tutorial</li> </ul>"},{"location":"tags/#dotfiles","title":"dotfiles","text":"<ul> <li>Bash's behaviour</li> </ul>"},{"location":"tags/#double","title":"double","text":"<ul> <li>Quotes and escaping</li> </ul>"},{"location":"tags/#doublequotes","title":"doublequotes","text":"<ul> <li>Quotes and escaping</li> </ul>"},{"location":"tags/#download","title":"download","text":"<ul> <li>Small code snipplets</li> </ul>"},{"location":"tags/#ed","title":"ed","text":"<ul> <li>Editing files via scripts with ed</li> </ul>"},{"location":"tags/#edit","title":"edit","text":"<ul> <li>Editing files via scripts with ed</li> </ul>"},{"location":"tags/#editor","title":"editor","text":"<ul> <li>Editing files via scripts with ed</li> </ul>"},{"location":"tags/#environment","title":"environment","text":"<ul> <li>Bash and the process tree</li> </ul>"},{"location":"tags/#escape","title":"escape","text":"<ul> <li>Generate code with own arguments properly quoted</li> <li>Quotes and escaping</li> </ul>"},{"location":"tags/#example","title":"example","text":"<ul> <li>Collapsing Functions</li> <li>Small code snipplets</li> </ul>"},{"location":"tags/#execute","title":"execute","text":"<ul> <li>Command substitution</li> </ul>"},{"location":"tags/#executing","title":"executing","text":"<ul> <li>Parser exec</li> </ul>"},{"location":"tags/#execution","title":"execution","text":"<ul> <li>Parser exec</li> </ul>"},{"location":"tags/#expansion","title":"expansion","text":"<ul> <li>Parameter expansion</li> <li>Brace expansion</li> <li>Command substitution</li> <li>Expansions and substitutions</li> <li>Process substitution</li> <li>Tilde expansion</li> </ul>"},{"location":"tags/#file","title":"file","text":"<ul> <li>Editing files via scripts with ed</li> <li>Illustrated Redirection Tutorial</li> </ul>"},{"location":"tags/#filename","title":"filename","text":"<ul> <li>Patterns and pattern matching</li> <li>Expansions and substitutions</li> </ul>"},{"location":"tags/#files","title":"files","text":"<ul> <li>Config files for your script</li> <li>Bash's behaviour</li> </ul>"},{"location":"tags/#function","title":"function","text":"<ul> <li>Collapsing Functions</li> </ul>"},{"location":"tags/#generate","title":"generate","text":"<ul> <li>Generate code with own arguments properly quoted</li> </ul>"},{"location":"tags/#getopt","title":"getopt","text":"<ul> <li>Small getopts tutorial</li> </ul>"},{"location":"tags/#getopts","title":"getopts","text":"<ul> <li>Small getopts tutorial</li> </ul>"},{"location":"tags/#glob","title":"glob","text":"<ul> <li>Patterns and pattern matching</li> </ul>"},{"location":"tags/#globbing","title":"globbing","text":"<ul> <li>Patterns and pattern matching</li> </ul>"},{"location":"tags/#grammar","title":"grammar","text":"<ul> <li>Basic grammar rules of Bash</li> </ul>"},{"location":"tags/#home","title":"home","text":"<ul> <li>Tilde expansion</li> </ul>"},{"location":"tags/#homedir","title":"homedir","text":"<ul> <li>Tilde expansion</li> </ul>"},{"location":"tags/#include","title":"include","text":"<ul> <li>Config files for your script</li> </ul>"},{"location":"tags/#integer","title":"integer","text":"<ul> <li>Arithmetic expressions</li> </ul>"},{"location":"tags/#language","title":"language","text":"<ul> <li>Basic grammar rules of Bash</li> <li>Parser exec</li> </ul>"},{"location":"tags/#learning","title":"learning","text":"<ul> <li>The basics of shell scripting</li> </ul>"},{"location":"tags/#linux","title":"linux","text":"<ul> <li>Start</li> </ul>"},{"location":"tags/#list","title":"list","text":"<ul> <li>Brace expansion</li> </ul>"},{"location":"tags/#locking","title":"locking","text":"<ul> <li>Lock your script (against parallel execution)</li> </ul>"},{"location":"tags/#macro","title":"macro","text":"<ul> <li>Expansions and substitutions</li> </ul>"},{"location":"tags/#mangle","title":"mangle","text":"<ul> <li>Parameter expansion</li> </ul>"},{"location":"tags/#marks","title":"marks","text":"<ul> <li>Quotes and escaping</li> </ul>"},{"location":"tags/#matching","title":"matching","text":"<ul> <li>Patterns and pattern matching</li> </ul>"},{"location":"tags/#math","title":"math","text":"<ul> <li>Arithmetic expressions</li> </ul>"},{"location":"tags/#modes","title":"modes","text":"<ul> <li>Bash's behaviour</li> </ul>"},{"location":"tags/#mutex","title":"mutex","text":"<ul> <li>Lock your script (against parallel execution)</li> </ul>"},{"location":"tags/#null","title":"null","text":"<ul> <li>Parameter expansion</li> </ul>"},{"location":"tags/#obsolete","title":"obsolete","text":"<ul> <li>Obsolete and deprecated syntax</li> </ul>"},{"location":"tags/#options","title":"options","text":"<ul> <li>Small getopts tutorial</li> <li>List of shell options</li> <li>Handling positional parameters</li> </ul>"},{"location":"tags/#outdated","title":"outdated","text":"<ul> <li>Obsolete and deprecated syntax</li> </ul>"},{"location":"tags/#output","title":"output","text":"<ul> <li>Command substitution</li> </ul>"},{"location":"tags/#packing","title":"packing","text":"<ul> <li>pax - the POSIX archiver</li> </ul>"},{"location":"tags/#parameter","title":"parameter","text":"<ul> <li>Parameter expansion</li> </ul>"},{"location":"tags/#parameters","title":"parameters","text":"<ul> <li>Small getopts tutorial</li> <li>Handling positional parameters</li> </ul>"},{"location":"tags/#pattern","title":"pattern","text":"<ul> <li>Patterns and pattern matching</li> </ul>"},{"location":"tags/#pipes","title":"pipes","text":"<ul> <li>Bash and the process tree</li> </ul>"},{"location":"tags/#pitfalls","title":"pitfalls","text":"<ul> <li>Beginner Mistakes</li> </ul>"},{"location":"tags/#portability","title":"portability","text":"<ul> <li>Portability talk</li> </ul>"},{"location":"tags/#portable","title":"portable","text":"<ul> <li>Portability talk</li> </ul>"},{"location":"tags/#positional","title":"positional","text":"<ul> <li>Small getopts tutorial</li> <li>Handling positional parameters</li> </ul>"},{"location":"tags/#processes","title":"processes","text":"<ul> <li>Bash and the process tree</li> </ul>"},{"location":"tags/#quote","title":"quote","text":"<ul> <li>Generate code with own arguments properly quoted</li> </ul>"},{"location":"tags/#quotes","title":"quotes","text":"<ul> <li>Quotes and escaping</li> </ul>"},{"location":"tags/#quoting","title":"quoting","text":"<ul> <li>Generate code with own arguments properly quoted</li> <li>Quotes and escaping</li> </ul>"},{"location":"tags/#recognition","title":"recognition","text":"<ul> <li>Words...</li> </ul>"},{"location":"tags/#redirect","title":"redirect","text":"<ul> <li>Illustrated Redirection Tutorial</li> </ul>"},{"location":"tags/#redirection","title":"redirection","text":"<ul> <li>Illustrated Redirection Tutorial</li> </ul>"},{"location":"tags/#result","title":"result","text":"<ul> <li>Command substitution</li> </ul>"},{"location":"tags/#return","title":"return","text":"<ul> <li>Command substitution</li> </ul>"},{"location":"tags/#run-control","title":"run-control","text":"<ul> <li>Lock your script (against parallel execution)</li> </ul>"},{"location":"tags/#runtime","title":"runtime","text":"<ul> <li>List of shell options</li> </ul>"},{"location":"tags/#save","title":"save","text":"<ul> <li>Command substitution</li> <li>Process substitution</li> </ul>"},{"location":"tags/#scripting","title":"scripting","text":"<ul> <li>Start</li> <li>Calculating with dc</li> <li>Collapsing Functions</li> <li>Config files for your script</li> <li>Editing files via scripts with ed</li> <li>Small getopts tutorial</li> <li>Lock your script (against parallel execution)</li> <li>pax - the POSIX archiver</li> <li>Illustrated Redirection Tutorial</li> <li>List of shell options</li> <li>Bash's behaviour</li> <li>The basics of shell scripting</li> <li>Debugging a script</li> <li>Beginner Mistakes</li> <li>Portability talk</li> <li>Obsolete and deprecated syntax</li> <li>Handling positional parameters</li> <li>Bash and the process tree</li> <li>Terminal codes (ANSI/VT100) introduction</li> <li>Small code snipplets</li> <li>Arithmetic expressions</li> <li>Basic grammar rules of Bash</li> <li>Patterns and pattern matching</li> <li>Parameter expansion</li> <li>Quotes and escaping</li> <li>Words...</li> <li>Brace expansion</li> <li>Command substitution</li> <li>Expansions and substitutions</li> <li>Process substitution</li> <li>Tilde expansion</li> <li>Parser exec</li> </ul>"},{"location":"tags/#sed","title":"sed","text":"<ul> <li>Editing files via scripts with ed</li> </ul>"},{"location":"tags/#shell","title":"shell","text":"<ul> <li>Start</li> <li>Calculating with dc</li> <li>Collapsing Functions</li> <li>Config files for your script</li> <li>Editing files via scripts with ed</li> <li>Small getopts tutorial</li> <li>Lock your script (against parallel execution)</li> <li>pax - the POSIX archiver</li> <li>Illustrated Redirection Tutorial</li> <li>List of shell options</li> <li>Bash's behaviour</li> <li>The basics of shell scripting</li> <li>Debugging a script</li> <li>Beginner Mistakes</li> <li>Portability talk</li> <li>Obsolete and deprecated syntax</li> <li>Handling positional parameters</li> <li>Bash and the process tree</li> <li>Terminal codes (ANSI/VT100) introduction</li> <li>Small code snipplets</li> <li>Arithmetic expressions</li> <li>Basic grammar rules of Bash</li> <li>Patterns and pattern matching</li> <li>Parameter expansion</li> <li>Quotes and escaping</li> <li>Words...</li> <li>Brace expansion</li> <li>Command substitution</li> <li>Expansions and substitutions</li> <li>Process substitution</li> <li>Tilde expansion</li> <li>Parser exec</li> </ul>"},{"location":"tags/#shortcut","title":"shortcut","text":"<ul> <li>Tilde expansion</li> </ul>"},{"location":"tags/#single","title":"single","text":"<ul> <li>Quotes and escaping</li> </ul>"},{"location":"tags/#singlequotes","title":"singlequotes","text":"<ul> <li>Quotes and escaping</li> </ul>"},{"location":"tags/#snipplet","title":"snipplet","text":"<ul> <li>Small code snipplets</li> </ul>"},{"location":"tags/#split","title":"split","text":"<ul> <li>Words...</li> </ul>"},{"location":"tags/#splitting","title":"splitting","text":"<ul> <li>Words...</li> </ul>"},{"location":"tags/#startup","title":"startup","text":"<ul> <li>Bash's behaviour</li> </ul>"},{"location":"tags/#stdin","title":"stdin","text":"<ul> <li>Process substitution</li> </ul>"},{"location":"tags/#stdout","title":"stdout","text":"<ul> <li>Command substitution</li> <li>Process substitution</li> </ul>"},{"location":"tags/#substitute","title":"substitute","text":"<ul> <li>Parameter expansion</li> </ul>"},{"location":"tags/#substitution","title":"substitution","text":"<ul> <li>Parameter expansion</li> <li>Brace expansion</li> <li>Command substitution</li> <li>Expansions and substitutions</li> <li>Process substitution</li> <li>Tilde expansion</li> </ul>"},{"location":"tags/#syntax","title":"syntax","text":"<ul> <li>Basic grammar rules of Bash</li> <li>Parser exec</li> </ul>"},{"location":"tags/#tar","title":"tar","text":"<ul> <li>pax - the POSIX archiver</li> </ul>"},{"location":"tags/#text","title":"text","text":"<ul> <li>Parameter expansion</li> <li>Brace expansion</li> <li>Command substitution</li> <li>Expansions and substitutions</li> <li>Process substitution</li> </ul>"},{"location":"tags/#tilde","title":"tilde","text":"<ul> <li>Tilde expansion</li> </ul>"},{"location":"tags/#token","title":"token","text":"<ul> <li>Words...</li> </ul>"},{"location":"tags/#traps","title":"traps","text":"<ul> <li>Beginner Mistakes</li> </ul>"},{"location":"tags/#tutorial","title":"tutorial","text":"<ul> <li>Illustrated Redirection Tutorial</li> <li>The basics of shell scripting</li> </ul>"},{"location":"tags/#value","title":"value","text":"<ul> <li>Command substitution</li> </ul>"},{"location":"tags/#variable","title":"variable","text":"<ul> <li>List of shell options</li> <li>Parameter expansion</li> <li>Command substitution</li> <li>Expansions and substitutions</li> </ul>"},{"location":"tags/#variables","title":"variables","text":"<ul> <li>Bash and the process tree</li> </ul>"},{"location":"tags/#vt100","title":"vt100","text":"<ul> <li>Terminal codes (ANSI/VT100) introduction</li> </ul>"},{"location":"tags/#wildcard","title":"wildcard","text":"<ul> <li>Expansions and substitutions</li> </ul>"},{"location":"tags/#wildcards","title":"wildcards","text":"<ul> <li>Patterns and pattern matching</li> </ul>"},{"location":"tags/#words","title":"words","text":"<ul> <li>Words...</li> </ul>"},{"location":"tags/#wrapper","title":"wrapper","text":"<ul> <li>Generate code with own arguments properly quoted</li> </ul>"},{"location":"tags/#zip","title":"zip","text":"<ul> <li>pax - the POSIX archiver</li> </ul>"}]}