summaryrefslogtreecommitdiff
path: root/gemfeed/2022-01-01-bash-golf-part-2.html
diff options
context:
space:
mode:
Diffstat (limited to 'gemfeed/2022-01-01-bash-golf-part-2.html')
-rw-r--r--gemfeed/2022-01-01-bash-golf-part-2.html66
1 files changed, 33 insertions, 33 deletions
diff --git a/gemfeed/2022-01-01-bash-golf-part-2.html b/gemfeed/2022-01-01-bash-golf-part-2.html
index 2402525b..2666ee3c 100644
--- a/gemfeed/2022-01-01-bash-golf-part-2.html
+++ b/gemfeed/2022-01-01-bash-golf-part-2.html
@@ -19,7 +19,7 @@
/ / . / / .' . |
jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Art by Joan Stark, mod. by Paul Buetow
-</pre>
+</pre><br />
<p class="quote"><i>Published by Paul at 2022-01-01, last updated at 2022-01-05</i></p>
<p>This is the second blog post about my Bash Golf series. This series is random Bash tips, tricks and weirdnesses I came across. It's a collection of smaller articles I wrote in an older (in German language) blog, which I translated and refreshed with some new content.</p>
<a class="textlink" href="./2021-11-29-bash-golf-part-1.html">Bash Golf Part 1</a><br />
@@ -39,14 +39,14 @@ lrwx------. 1 paul paul 64 Nov 23 09:46 0 -&gt; /dev/pts/9
lrwx------. 1 paul paul 64 Nov 23 09:46 1 -&gt; /dev/pts/9
lrwx------. 1 paul paul 64 Nov 23 09:46 2 -&gt; /dev/pts/9
lr-x------. 1 paul paul 64 Nov 23 09:46 3 -&gt; /proc/162912/fd
-</pre>
+</pre><br />
<p>The following examples demonstrate two different ways to accomplish the same thing. The difference is that the first command is directly printing out "Foo" to stdout and the second command is explicitly redirecting stdout to its own stdout file descriptor:</p>
<pre>
❯ echo Foo
Foo
❯ echo Foo &gt; /proc/self/fd/0
Foo
-</pre>
+</pre><br />
<p>Other useful redirections are:</p>
<ul>
<li>Redirect stderr to stdin: "echo foo 2&gt;&amp;1"</li>
@@ -56,13 +56,13 @@ Foo
<pre>
❯ echo Foo 1&gt;&amp;2 2&gt;/dev/null
Foo
-</pre>
+</pre><br />
<p class="quote"><i>Update: A reader sent me an email and pointed out that the order of the redirections is important. </i></p>
<p>As you can see, the following will not print out anything:</p>
<pre>
❯ echo Foo 2&gt;/dev/null 1&gt;&amp;2
-</pre>
+</pre><br />
<p>A good description (also pointed out by the reader) can be found here:</p>
<a class="textlink" href="https://wiki.bash-hackers.org/howto/redirection_tutorial#order_of_redirection_ie_file_2_1_vs_2_1_file">Order of redirection</a><br />
<p>Ok, back to the original blog post. You can also use grouping here (neither of these commands will print out anything to stdout):</p>
@@ -72,7 +72,7 @@ Foo
❯ { { { echo Foo 1&gt;&amp;2; } 2&gt;&amp;1; } 1&gt;&amp;2; } 2&gt;/dev/null
❯ ( ( ( echo Foo 1&gt;&amp;2; ) 2&gt;&amp;1; ) 1&gt;&amp;2; ) 2&gt;/dev/null
-</pre>
+</pre><br />
<p>A handy way to list all open file descriptors is to use the "lsof" command (that's not a Bash built-in), whereas $$ is the process id (pid) of the current shell process:</p>
<pre>
❯ lsof -a -p $$ -d0,1,2
@@ -80,7 +80,7 @@ COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
bash 62676 paul 0u CHR 136,9 0t0 12 /dev/pts/9
bash 62676 paul 1u CHR 136,9 0t0 12 /dev/pts/9
bash 62676 paul 2u CHR 136,9 0t0 12 /dev/pts/9
-</pre>
+</pre><br />
<p>Let's create our own descriptor "3" for redirection to a file named "foo":</p>
<pre>
❯ touch foo
@@ -95,7 +95,7 @@ Bratwurst
❯ exec 3&gt;&amp;- # This closes fd 3.
❯ echo Steak &gt;&amp;3
-bash: 3: Bad file descriptor
-</pre>
+</pre><br />
<p>You can also override the default file descriptors, as the following example script demonstrates:</p>
<pre>
❯ cat grandmaster.sh
@@ -122,14 +122,14 @@ echo Second line: $LINE2
# Restore default stdin and delete fd 6
exec 0&lt;&amp;6 6&lt;&amp;-
-</pre>
+</pre><br />
<p>Let's execute it:</p>
<pre>
❯ chmod 750 ./grandmaster.sh
❯ ./grandmaster.sh
First line: Learn You a Haskell
Second line: for Great Good
-</pre>
+</pre><br />
<h2>HERE</h2>
<p>I have mentioned HERE-documents and HERE-strings already in this post. Let's do some more examples. The following "cat" receives a multi line string from stdin. In this case, the input multi line string is a HERE-document. As you can see, it also interpolates variables (in this case the output of "date" running in a subshell).</p>
<pre>
@@ -139,7 +139,7 @@ Second line: for Great Good
&gt; END
Hello World
It's Fri 26 Nov 08:46:52 GMT 2021
-</pre>
+</pre><br />
<p>You can also write it the following way, but that's less readable (it's good for an obfuscation contest):</p>
<pre>
❯ &lt;&lt;END cat
@@ -148,7 +148,7 @@ It's Fri 26 Nov 08:46:52 GMT 2021
&gt; END
Hello Universe
It's Fri 26 Nov 08:47:32 GMT 2021
-</pre>
+</pre><br />
<p>Besides of an HERE-document, there is also a so-called HERE-string. Besides of...</p>
<pre>
❯ declare VAR=foo
@@ -156,24 +156,24 @@ It's Fri 26 Nov 08:47:32 GMT 2021
&gt; echo '$VAR ontains foo'
&gt; fi
$VAR ontains foo
-</pre>
+</pre><br />
<p>...you can use a HERE-string like that:</p>
<pre>
❯ if grep -q foo &lt;&lt;&lt; "$VAR"; then
&gt; echo '$VAR contains foo'
&gt; fi
$VAR contains foo
-</pre>
+</pre><br />
<p>Or even shorter, you can do:</p>
<pre>
❯ grep -q foo &lt;&lt;&lt; "$VAR" &amp;&amp; echo '$VAR contains foo'
$VAR contains foo
-</pre>
+</pre><br />
<p>You can also use a Bash regex to accomplish the same thing, but the points of the examples so far were to demonstrate HERE-{documents,strings} and not Bash regular expressions:</p>
<pre>
❯ if [[ "$VAR" =~ foo ]]; then echo yay; fi
yay
-</pre>
+</pre><br />
<p>You can also use it with "read":</p>
<pre>
❯ read a &lt;&lt;&lt; ja
@@ -188,14 +188,14 @@ NEIN!!!
Learn
❯ echo ${words[3]}
Golang
-</pre>
+</pre><br />
<p>The following is good for an obfuscation contest too:</p>
<pre>
❯ echo 'I like Perl too' &gt; perllove.txt
❯ cat - perllove.txt &lt;&lt;&lt; "$dumdidumstring"
Learn you a Golang for Great Good
I like Perl too
-</pre>
+</pre><br />
<h2>RANDOM</h2>
<p>Random is a special built-in variable containing a different pseudo random number each time it's used.</p>
<pre>
@@ -205,7 +205,7 @@ I like Perl too
14997
❯ echo $RANDOM
9104
-</pre>
+</pre><br />
<p>That's very useful if you want to randomly delay the execution of your scripts when you run it on many servers concurrently, just to spread the server load (which might be caused by the script run) better.</p>
<p>Let's say you want to introduce a random delay of 1 minute. You can accomplish it with:</p>
<pre>
@@ -234,7 +234,7 @@ main
❯ ./calc_answer_to_ultimate_question_in_life.sh
Delaying script execution for 42 seconds...
Continuing script execution...
-</pre>
+</pre><br />
<h2>set -x and set -e and pipefile</h2>
<p>In my opinion, -x and -e and pipefile are the most useful Bash options. Let's have a look at them one after another.</p>
<h3>-x</h3>
@@ -249,11 +249,11 @@ Continuing script execution...
++ echo 121
+ echo 'Square of 11 is 121'
Square of 11 is 121
-</pre>
+</pre><br />
<p>You can also set it when calling an external script without modifying the script itself:</p>
<pre>
❯ bash -x ./half_broken_script_to_be_debugged.sh
-</pre>
+</pre><br />
<p>Let's do that on one of the example scripts we covered earlier:</p>
<pre>
❯ bash -x ./grandmaster.sh
@@ -271,21 +271,21 @@ First line: Learn You a Haskell
Second line: for Great Good
+ exec
-</pre>
+</pre><br />
<h3>-e</h3>
<p>This is a very important option you want to use when you are paranoid. This means, you should always "set -e" in your scripts when you need to make absolutely sure that your script runs successfully (with that I mean that no command should exit with an unexpected status code).</p>
<p>Ok, let's dig deeper:</p>
<pre>
❯ help set | grep -- -e
-e Exit immediately if a command exits with a non-zero status.
-</pre>
+</pre><br />
<p>As you can see in the following example, the Bash terminates after the execution of "grep" as "foo" is not matching "bar". Therefore, grep exits with 1 (unsuccessfully) and the shell aborts. And therefore, "bar" will not be printed out anymore:</p>
<pre>
❯ bash -c 'set -e; echo hello; grep -q bar &lt;&lt;&lt; foo; echo bar'
hello
❯ echo $?
1
-</pre>
+</pre><br />
<p>Whereas the outcome changes when the regex matches:</p>
<pre>
❯ bash -c 'set -e; echo hello; grep -q bar &lt;&lt;&lt; barman; echo bar'
@@ -293,7 +293,7 @@ hello
bar
❯ echo $?
0
-</pre>
+</pre><br />
<p>So does it mean that grep will always make the shell terminate whenever its exit code isn't 0? This will render "set -e" quite unusable. Frankly, there are other commands where an exit status other than 0 should not terminate the whole script abruptly. Usually, what you want is to branch your code based on the outcome (exit code) of a command:</p>
<pre>
❯ bash -c 'set -e
@@ -305,7 +305,7 @@ bar
&gt; fi'
❯ echo $?
1
-</pre>
+</pre><br />
<p>...but the example above won't reach any of the branches and won't print out anything, as the script terminates right after grep.</p>
<p>The proper solution is to use grep as an expression in a conditional (e.g. in an if-else statement):</p>
<pre>
@@ -327,7 +327,7 @@ not matching
matching
❯ echo $?
0
-</pre>
+</pre><br />
<p>You can also temporally undo "set -e" if there is no other way:</p>
<pre>
❯ cat ./e.sh
@@ -369,7 +369,7 @@ foo
Hello World
Hello Universe
Hello You!
-</pre>
+</pre><br />
<p>Why does calling "foo" with no arguments make the script terminate? Because as no argument was given, the "shift" won't have anything to do as the argument list $@ is empty, and therefore "shift" fails with a non-zero status.</p>
<p>Why would you want to use "shift" after function-local variable assignments? Have a look at my personal Bash coding style guide for an explanation :-):</p>
<a class="textlink" href="./2021-05-16-personal-bash-coding-style-guide.html">./2021-05-16-personal-bash-coding-style-guide.html</a><br />
@@ -380,14 +380,14 @@ Hello You!
pipefail the return value of a pipeline is the status of
the last command to exit with a non-zero status,
or zero if no command exited with a non-zero status
-</pre>
+</pre><br />
<p>The following greps for paul in passwd and converts all lowercase letters to uppercase letters. The exit code of the pipe is 0, as the last command of the pipe (converting from lowercase to uppercase) succeeded:</p>
<pre>
❯ grep paul /etc/passwd | tr '[a-z]' '[A-Z]'
PAUL:X:1000:1000:PAUL BUETOW:/HOME/PAUL:/BIN/BASH
❯ echo $?
0
-</pre>
+</pre><br />
<p>Let's look at another example, where "TheRock" doesn't exist in the passwd file. However, the pipes exit status is still 0 (success). This is so because the last command ("tr" in this case) still succeeded. It is just that it didn't get any input on stdin to process:</p>
<pre>
❯ grep TheRock /etc/passwd
@@ -396,14 +396,14 @@ PAUL:X:1000:1000:PAUL BUETOW:/HOME/PAUL:/BIN/BASH
❯ grep TheRock /etc/passwd | tr '[a-z]' '[A-Z]'
❯ echo $?
0
-</pre>
+</pre><br />
<p>To change this behaviour, pipefile can be used. Now, the pipes exit status is 1 (fail), because the pipe contains at least one command (in this case grep) which exited with status 1:</p>
<pre>
❯ set -o pipefail
❯ grep TheRock /etc/passwd | tr '[a-z]' '[A-Z]'
❯ echo $?
1
-</pre>
+</pre><br />
<p>E-Mail me your comments to paul at buetow dot org!</p>
<a class="textlink" href="../">Go back to the main site</a><br />
<p class="footer">