diff options
| author | Paul Buetow <paul@buetow.org> | 2021-11-30 21:58:45 +0000 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2021-11-30 21:58:45 +0000 |
| commit | da1fc057fb17a8767f0ac6da3cbadff62739fc96 (patch) | |
| tree | 6bc3df4b30b8ce4eab9ae34a86b28c0a2686e645 /gemfeed | |
| parent | 615ef5ac4ac8827d22ce7fe45884d2a9380ebf9d (diff) | |
Publishing new version
Diffstat (limited to 'gemfeed')
24 files changed, 940 insertions, 21 deletions
diff --git a/gemfeed/2008-06-26-perl-poetry.md b/gemfeed/2008-06-26-perl-poetry.md index 7a12e865..651ee057 100644 --- a/gemfeed/2008-06-26-perl-poetry.md +++ b/gemfeed/2008-06-26-perl-poetry.md @@ -23,7 +23,7 @@ _~~|~/_|_|__/|~~~~~~~ | / ~~~~~ | | ~~~~~~~~ (__) (____) ``` -> Written by Paul Buetow 2008-06-26, last updated 2021-05-04 +> Published by Paul Buetow 2008-06-26, last updated 2021-05-04 Here are some Perl Poems I wrote. They don't do anything useful when you run them, but they don't produce a compiler error either. They only exist for fun and demonstrate what you can do with Perl syntax. diff --git a/gemfeed/2010-04-09-standard-ml-and-haskell.md b/gemfeed/2010-04-09-standard-ml-and-haskell.md index 90212b66..2f9273da 100644 --- a/gemfeed/2010-04-09-standard-ml-and-haskell.md +++ b/gemfeed/2010-04-09-standard-ml-and-haskell.md @@ -1,6 +1,6 @@ # Standard ML and Haskell -> Written by Paul Buetow 2010-04-09 +> Published by Paul Buetow 2010-04-09 I am currently looking into the functional programming language Standard ML (aka SML). The purpose is to refresh my functional programming skills and to learn something new too. Since I already knew a little Haskell, I could not help myself, and I also implemented the same exercises in Haskell. diff --git a/gemfeed/2010-05-07-lazy-evaluation-with-standarn-ml.md b/gemfeed/2010-05-07-lazy-evaluation-with-standarn-ml.md index a0bb35cf..6725e2bc 100644 --- a/gemfeed/2010-05-07-lazy-evaluation-with-standarn-ml.md +++ b/gemfeed/2010-05-07-lazy-evaluation-with-standarn-ml.md @@ -13,7 +13,7 @@ `|||| ``` -> Written by Paul Buetow 2010-05-07 +> Published by Paul Buetow 2010-05-07 In contrast to Haskell, Standard SML does not use lazy evaluation by default but an eager evaluation. diff --git a/gemfeed/2010-05-09-the-fype-programming-language.md b/gemfeed/2010-05-09-the-fype-programming-language.md index 1a133b2c..cec28628 100644 --- a/gemfeed/2010-05-09-the-fype-programming-language.md +++ b/gemfeed/2010-05-09-the-fype-programming-language.md @@ -9,7 +9,7 @@ |___/|_| |___/ |___/ ``` -> Written by Paul Buetow 2010-05-09, last updated 2021-05-05 +> Published by Paul Buetow 2010-05-09, last updated 2021-05-05 Fype is an interpreted programming language created by me for learning and fun. The interpreter is written in C. It has been tested on FreeBSD and NetBSD and may also work on other Unix like operating systems such as Linux based ones. Besides learning and fun, there is no other use case of why Fype exists as many other programming languages are much faster and more powerful. diff --git a/gemfeed/2011-05-07-perl-daemon-service-framework.md b/gemfeed/2011-05-07-perl-daemon-service-framework.md index b12c287e..bad1873b 100644 --- a/gemfeed/2011-05-07-perl-daemon-service-framework.md +++ b/gemfeed/2011-05-07-perl-daemon-service-framework.md @@ -7,7 +7,7 @@ //\ //\\ //\ //\\ //\ //\\jrei ``` -> Written by Paul Buetow 2011-05-07, last updated 2021-05-07 +> Published by Paul Buetow 2011-05-07, last updated 2021-05-07 PerlDaemon is a minimal daemon for Linux and other Unix like operating systems programmed in Perl. It is a minimal but pretty functional and fairly generic service framework. This means that it does not do anything useful other than providing a framework for starting, stopping, configuring and logging. To do something useful, a module (written in Perl) must be provided. diff --git a/gemfeed/2014-03-24-the-fibonacci.pl.c-polyglot.md b/gemfeed/2014-03-24-the-fibonacci.pl.c-polyglot.md index f1b5553e..64e579a3 100644 --- a/gemfeed/2014-03-24-the-fibonacci.pl.c-polyglot.md +++ b/gemfeed/2014-03-24-the-fibonacci.pl.c-polyglot.md @@ -1,6 +1,6 @@ # The fibonacci.pl.c Polyglot -> Written by Paul Buetow 2014-03-24 +> Published by Paul Buetow 2014-03-24 In computing, a polyglot is a computer program or script written in a valid form of multiple programming languages, which performs the same operations or output independent of the programming language used to compile or interpret it. diff --git a/gemfeed/2015-12-05-run-debian-on-your-phone-with-debroid.md b/gemfeed/2015-12-05-run-debian-on-your-phone-with-debroid.md index bf17aaca..54c331cf 100644 --- a/gemfeed/2015-12-05-run-debian-on-your-phone-with-debroid.md +++ b/gemfeed/2015-12-05-run-debian-on-your-phone-with-debroid.md @@ -9,7 +9,7 @@ ``` -> Written by Paul Buetow 2015-12-05, last updated 2021-05-16 +> Published by Paul Buetow 2015-12-05, last updated 2021-05-16 You can use the following tutorial to install a full-blown Debian GNU/Linux Chroot on an LG G3 D855 CyanogenMod 13 (Android 6). First of all, you need to have root permissions on your phone, and you also need to have the developer mode activated. The following steps have been tested on Linux (Fedora 23). diff --git a/gemfeed/2016-04-03-offsite-backup-with-zfs.md b/gemfeed/2016-04-03-offsite-backup-with-zfs.md index 2c6477af..6980d6c4 100644 --- a/gemfeed/2016-04-03-offsite-backup-with-zfs.md +++ b/gemfeed/2016-04-03-offsite-backup-with-zfs.md @@ -13,7 +13,7 @@ \____||__|_____|__| ``` -> Written by Paul Buetow 2016-04-03 +> Published by Paul Buetow 2016-04-03 ## Please don't lose all my pictures again! diff --git a/gemfeed/2016-04-09-jails-and-zfs-on-freebsd-with-puppet.md b/gemfeed/2016-04-09-jails-and-zfs-on-freebsd-with-puppet.md index ad2fdaba..553455b4 100644 --- a/gemfeed/2016-04-09-jails-and-zfs-on-freebsd-with-puppet.md +++ b/gemfeed/2016-04-09-jails-and-zfs-on-freebsd-with-puppet.md @@ -20,7 +20,7 @@ \ `. ``` -> Written by Paul Buetow 2016-04-09 +> Published by Paul Buetow 2016-04-09 Over the last couple of years I wrote quite a few Puppet modules in order to manage my personal server infrastructure. One of them manages FreeBSD Jails and another one ZFS file systems. I thought I would give a brief overview in how it looks and feels. diff --git a/gemfeed/2016-04-16-offsite-backup-with-zfs-part2.md b/gemfeed/2016-04-16-offsite-backup-with-zfs-part2.md index af21526b..78946f13 100644 --- a/gemfeed/2016-04-16-offsite-backup-with-zfs-part2.md +++ b/gemfeed/2016-04-16-offsite-backup-with-zfs-part2.md @@ -15,7 +15,7 @@ \____||__|_____|__| ``` -> Written by Paul Buetow 2016-04-16 +> Published by Paul Buetow 2016-04-16 [Read the first part before reading any furter here...](./2016-04-03-offsite-backup-with-zfs.md) diff --git a/gemfeed/2016-05-22-spinning-up-my-own-authoritative-dns-servers.md b/gemfeed/2016-05-22-spinning-up-my-own-authoritative-dns-servers.md index f73aef98..f4bc6720 100644 --- a/gemfeed/2016-05-22-spinning-up-my-own-authoritative-dns-servers.md +++ b/gemfeed/2016-05-22-spinning-up-my-own-authoritative-dns-servers.md @@ -1,6 +1,6 @@ # Spinning up my own authoritative DNS servers -> Written by Paul Buetow 2016-05-22 +> Published by Paul Buetow 2016-05-22 ## Background diff --git a/gemfeed/2016-11-20-methods-in-c.md b/gemfeed/2016-11-20-methods-in-c.md index 8f0516d1..ff7f320b 100644 --- a/gemfeed/2016-11-20-methods-in-c.md +++ b/gemfeed/2016-11-20-methods-in-c.md @@ -1,6 +1,6 @@ # Methods in C -> Written by Paul Buetow 2016-11-20 +> Published by Paul Buetow 2016-11-20 You can do some sort of object-oriented programming in the C Programming Language. However, that is very limited. But also very easy and straightforward to use. diff --git a/gemfeed/2018-06-01-realistic-load-testing-with-ioriot-for-linux.md b/gemfeed/2018-06-01-realistic-load-testing-with-ioriot-for-linux.md index 77ee72ee..40646bb4 100644 --- a/gemfeed/2018-06-01-realistic-load-testing-with-ioriot-for-linux.md +++ b/gemfeed/2018-06-01-realistic-load-testing-with-ioriot-for-linux.md @@ -11,7 +11,7 @@ jgs\__/'---'\__/ ``` -> Written by Paul Buetow 2018-06-01, last updated 2021-05-08 +> Published by Paul Buetow 2018-06-01, last updated 2021-05-08 ## Foreword diff --git a/gemfeed/2021-04-22-dtail-the-distributed-log-tail-program.md b/gemfeed/2021-04-22-dtail-the-distributed-log-tail-program.md index bbd14424..0f5107ce 100644 --- a/gemfeed/2021-04-22-dtail-the-distributed-log-tail-program.md +++ b/gemfeed/2021-04-22-dtail-the-distributed-log-tail-program.md @@ -1,6 +1,6 @@ # DTail - The distributed log tail program -> Written by Paul Buetow 2021-04-22, last updated 2021-04-26 +> Published by Paul Buetow 2021-04-22, last updated 2021-04-26 [](./2021-04-22-dtail-the-distributed-log-tail-program/title.png) diff --git a/gemfeed/2021-04-24-welcome-to-the-geminispace.md b/gemfeed/2021-04-24-welcome-to-the-geminispace.md index b393c8a1..48a92629 100644 --- a/gemfeed/2021-04-24-welcome-to-the-geminispace.md +++ b/gemfeed/2021-04-24-welcome-to-the-geminispace.md @@ -1,6 +1,6 @@ # Welcome to the Geminispace -> Written by Paul Buetow 2021-04-24, last updated 2021-06-18, ASCII Art by Andy Hood +> Published by Paul Buetow 2021-04-24, last updated 2021-06-18, ASCII Art by Andy Hood Have you reached this article already via Gemini? It requires a Gemini client; web browsers such as Firefox, Chrome, Safari, etc., don't support the Gemini protocol. The Gemini address of this site (or the address of this capsule as people say in Geminispace) is: diff --git a/gemfeed/2021-05-16-personal-bash-coding-style-guide.md b/gemfeed/2021-05-16-personal-bash-coding-style-guide.md index 1917f53f..389152d0 100644 --- a/gemfeed/2021-05-16-personal-bash-coding-style-guide.md +++ b/gemfeed/2021-05-16-personal-bash-coding-style-guide.md @@ -13,7 +13,7 @@ "\__/"---------------"\__/"-+---+' ``` -> Written by Paul Buetow 2021-05-16 +> Published by Paul Buetow 2021-05-16 Lately, I have been polishing and writing a lot of Bash code. Not that I never wrote a lot of Bash, but now as I also looked through the Google Shell Style Guide, I thought it is time also to write my thoughts on that. I agree with that guide in most, but not in all points. diff --git a/gemfeed/2021-06-05-gemtexter-one-bash-script-to-rule-it-all.md b/gemfeed/2021-06-05-gemtexter-one-bash-script-to-rule-it-all.md index 2dcf0687..329bee6f 100644 --- a/gemfeed/2021-06-05-gemtexter-one-bash-script-to-rule-it-all.md +++ b/gemfeed/2021-06-05-gemtexter-one-bash-script-to-rule-it-all.md @@ -41,7 +41,7 @@ `+a:f:......jrei''' ``` -> Written by Paul Buetow 2021-06-05 +> Published by Paul Buetow 2021-06-05 You might have read my previous blog post about entering the Geminispace, where I pointed out the benefits of having and maintaining an internet presence there. This whole site (the blog and all other pages) is composed in the Gemtext markup language. diff --git a/gemfeed/2021-07-04-the-well-grounded-rubyist.md b/gemfeed/2021-07-04-the-well-grounded-rubyist.md index bbcd587f..65f3a5f5 100644 --- a/gemfeed/2021-07-04-the-well-grounded-rubyist.md +++ b/gemfeed/2021-07-04-the-well-grounded-rubyist.md @@ -1,6 +1,6 @@ # The Well-Grounded Rubyist -> Written by Paul Buetow 2021-07-04 +> Published by Paul Buetow 2021-07-04 When I was a Linux System Administrator, I have been programming in Perl for years. I still maintain some personal Perl programming projects (e.g. Xerl, guprecords, Loadbars). After switching jobs a couple of years ago (becoming a Site Reliability Engineer), I found Ruby (and some Python) widely used there. As I wanted to do something new, I decided to give Ruby a go. diff --git a/gemfeed/2021-08-01-on-being-pedantic-about-open-source.md b/gemfeed/2021-08-01-on-being-pedantic-about-open-source.md index b657b767..4007d9a0 100644 --- a/gemfeed/2021-08-01-on-being-pedantic-about-open-source.md +++ b/gemfeed/2021-08-01-on-being-pedantic-about-open-source.md @@ -12,7 +12,7 @@ '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^' LGB - Art by lgbearrd ``` -> Written by Paul Buetow 2021-08-01 +> Published by Paul Buetow 2021-08-01 I believe that it is essential to always have free and open-source alternatives to any kind of closed-source proprietary software available to choose from. But there are a couple of points you need to take into consideration. diff --git a/gemfeed/2021-09-12-keep-it-simple-and-stupid.md b/gemfeed/2021-09-12-keep-it-simple-and-stupid.md index eee1b011..6091c1a1 100644 --- a/gemfeed/2021-09-12-keep-it-simple-and-stupid.md +++ b/gemfeed/2021-09-12-keep-it-simple-and-stupid.md @@ -15,7 +15,7 @@ -------------------- -------------------- ``` -> Written by Paul Buetow 2021-09-12, last updated 2021-10-22 +> Published by Paul Buetow 2021-09-12, last updated 2021-10-22 A robust computer system must be kept simple and stupid (KISS). The fancier the system is, the more can break. Unfortunately, most systems tend to become complex and challenging to maintain in today's world. In the early days, so I was told, engineers understood every part of the system, but nowadays, we see more of the "lasagna" stack. One layer or framework is built on top of another layer, and in the end, nobody has got a clue what's going on. diff --git a/gemfeed/2021-10-22-defensive-devops.md b/gemfeed/2021-10-22-defensive-devops.md index d5086f41..24d8e4d3 100644 --- a/gemfeed/2021-10-22-defensive-devops.md +++ b/gemfeed/2021-10-22-defensive-devops.md @@ -10,7 +10,7 @@ ASCII Art by Clyde Watson ``` -> Written by Paul Buetow 2021-10-22 +> Published by Paul Buetow 2021-10-22 I have seen many different setups and infrastructures during my carreer. My roles always included front-line ad-hoc fire fighting production issues. This often involves identifying and fixing these under time pressure, without the comfort of 2-week-long SCRUM sprints and without an exhaustive QA process. I also wrote a lot of code (Bash, Ruby, Perl, Go, and a little Java), and I followed the typical software development process, but that did not always apply to critical production issues. diff --git a/gemfeed/2021-11-28-bash-golf-part-2.draft.md b/gemfeed/2021-11-28-bash-golf-part-2.draft.md new file mode 100644 index 00000000..0ba5c209 --- /dev/null +++ b/gemfeed/2021-11-28-bash-golf-part-2.draft.md @@ -0,0 +1,488 @@ +# Bash Golf Part 2 + +``` + + '\ . . |>18>> + \ . ' . | + O>> . 'o | + \ . | + /\ . | + / / .' | +jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Art by Joan Stark +``` + +> Published by Paul Buetow 2021-11-29 + +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. + +## Redirection + +Let's have a closer look at Bash redirection. As you might already know that there are 3 standard file descriptors: + +* 0 aka stdin (standard input) +* 1 aka stdout (standard output) +* 2 aka stderr (standard error output) + +These are most certainly the ones you are using on regular basis. "/proc/self/fd" lists all file descriptors which are open by the current process (in this case: the current bash shell itself): + +``` +❯ ls -l /proc/self/fd/ +total 0 +lrwx------. 1 paul paul 64 Nov 23 09:46 0 -> /dev/pts/9 +lrwx------. 1 paul paul 64 Nov 23 09:46 1 -> /dev/pts/9 +lrwx------. 1 paul paul 64 Nov 23 09:46 2 -> /dev/pts/9 +lr-x------. 1 paul paul 64 Nov 23 09:46 3 -> /proc/162912/fd +``` + +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: + +``` +❯ echo Foo +Foo +❯ echo Foo > /proc/self/fd/0 +Foo +``` + +Other useful redirections are: + +* Redirect stderr to stdin: "echo foo 2>&1" +* Redirect stdin to stderr: "echo foo >&2" + +It is, however, not possible to redirect multiple times within the same command. E.g. the following won't work. You would expect stdin to be redirected to stderr and then stderr to be redirected to /dev/null. But as the example shows, Foo is still printed out: + +``` +❯ echo Foo 1>&2 2>/dev/null +Foo +``` + +This is where you can use grouping (neither of these commands will print out anything to stdout): + +``` +❯ { echo Foo 1>&2; } 2>/dev/null +❯ ( echo Foo 1>&2; ) 2>/dev/null +❯ { { { echo Foo 1>&2; } 2>&1; } 1>&2; } 2>/dev/null +❯ ( ( ( echo Foo 1>&2; ) 2>&1; ) 1>&2; ) 2>/dev/null +❯ +``` + +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: + +``` +❯ lsof -a -p $$ -d0,1,2 +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 +``` + +Let's create our own descriptor "3" for redirection to a file named "foo": + +``` +❯ touch foo +❯ exec 3>foo # This opens fd 3 and binds it to file foo. +❯ ls -l /proc/self/fd/3 +l-wx------. 1 paul paul 64 Nov 23 10:10 \ + /proc/self/fd/3 -> /home/paul/foo +❯ cat foo +❯ echo Bratwurst >&3 +❯ cat foo +Bratwurst +❯ exec 3>&- # This closes fd 3. +❯ echo Steak >&3 +-bash: 3: Bad file descriptor +``` + +You can also override the default file descriptors, as the following example script demonstrates: + +``` +❯ cat grandmaster.sh +#!/usr/bin/env bash + +# Write a file data-file containing two lines +echo Learn You a Haskell > data-file +echo for Great Good >> data-file + +# Link fd with fd 6 (saves default stdin) +exec 6<&0 + +# Overwrite stdin with data-file +exec < data-file + +# Read the first two lines from it +declare LINE1 LINE2 +read LINE1 +read LINE2 + +# Print them +echo First line: $LINE1 +echo Second line: $LINE2 + +# Restore default stdin and delete fd 6 +exec 0<&6 6<&- +``` + +Let's execute it: + +``` +❯ chmod 750 ./grandmaster.sh +❯ ./grandmaster.sh +First line: Learn You a Haskell +Second line: for Great Good +``` + +## HERE + +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). + +``` +❯ cat <<END +> Hello World +> It’s $(date) +> END +Hello World +It's Fri 26 Nov 08:46:52 GMT 2021 +``` + +You can also write it the following way, but that's less readable (it's good for an obfuscation contest): + +``` +❯ <<END cat +> Hello Universe +> It’s $(date) +> END +Hello Universe +It's Fri 26 Nov 08:47:32 GMT 2021 +``` + +Besides of an HERE-document, there is also a so-called HERE-string. Besides of... + +``` +❯ declare VAR=foo +❯ if echo "$VAR" | grep -q foo; then +> echo '$VAR ontains foo' +> fi +$VAR ontains foo +``` + +...you can use a HERE-string like that: + +``` +❯ if grep -q foo <<< "$VAR"; then +> echo '$VAR contains foo' +> fi +$VAR contains foo +``` + +Or even shorter, you can do: + +``` +❯ grep -q foo <<< "$VAR" && echo '$VAR contains foo' +$VAR contains foo +``` + +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: + +``` +❯ if [[ "$VAR" =~ foo ]]; then echo yay; fi +yay +``` + +You can also use it with "read": + +``` +❯ read a <<< ja +❯ echo $a +ja +❯ read b <<< 'NEIN!!!' +❯ echo $b +NEIN!!! +❯ dumdidumstring='Learn you a Golang for Great Good' +❯ read -a words <<< "$dumdidumstring" +❯ echo ${words[0]} +Learn +❯ echo ${words[3]} +Golang +``` + +The following is good for an obfuscation contest too: + +``` +❯ echo 'I like Perl too' > perllove.txt +❯ cat - perllove.txt <<< "$dumdidumstring" +Learn you a Golang for Great Good +I like Perl too +``` + +## RANDOM + +Random is a special built-in variable containing a different pseudo random number each time it's used. + +``` +❯ echo $RANDOM +11811 +❯ echo $RANDOM +14997 +❯ echo $RANDOM +9104 +``` + +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. + +Let's say you want to introduce a random delay of 1 minute. You can accomplish it with: + +``` +❯ cat ./calc_answer_to_ultimate_question_in_life.sh +#!/usr/bin/env bash + +declare -i MAX_DELAY=60 + +random_delay () { + local -i sleep_for=$((RANDOM % MAX_DELAY)) + echo "Delaying script execution for $sleep_for seconds..." + sleep $sleep_for + echo 'Continuing script execution...' +} + +main () { + random_delay + # From here, do the real work. Calculating the answer to + # the ultimate question can take billions of years.... + : .... +} + +main + +❯ +❯ ./calc_answer_to_ultimate_question_in_life.sh +Delaying script execution for 42 seconds... +Continuing script execution... +``` + +## set -x and set -e and pipefile + +In my opinion, -x and -e and pipefile are the most useful Bash options. Let's have a look at them one after another. + +### -x + +-x prints commands and their arguments as they are executed. This helps to develop and debug your Bash code: + +``` +❯ set -x +❯ square () { local -i num=$1; echo $((num*num)); } +❯ num=11; echo "Square of $num is $(square $num)" ++ num=11 +++ square 11 +++ local -i num=11 +++ echo 121 ++ echo 'Square of 11 is 121' +Square of 11 is 121 +``` + +However, you need to set -x for any subshell as well in order to make it work there too: + +``` +❯ num=12; echo "Square of $num is $(set -x;square $num)" ++ num=12 +++ set -x +++ square 12 +++ local -i num=12 +++ echo 144 ++ echo 'Square of 12 is 144' +Square of 12 is 144 +❯ +``` + +You can also set it when calling an external script without modifying the script itself: + +``` +❯ bash -x ./half_broken_script_to_be_debugged.sh +``` + +Let's do that on one of the example scripts we covered earlier: + +``` +❯ bash -x ./grandmaster.sh ++ bash -x ./grandmaster.sh ++ echo Learn You a Haskell ++ echo for Great Good ++ exec ++ exec ++ declare LINE1 LINE2 ++ read LINE1 ++ read LINE2 ++ echo First line: Learn You a Haskell +First line: Learn You a Haskell ++ echo Second line: for Great Good +Second line: for Great Good ++ exec +❯ +``` + +### -e + +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). + +Before we dig dipper, this blog article of mine might interest you too, it describes more techniques to make your scripts running safely: + +[Defensive DevOps](./2021-10-22-defensive-devops.md) + +Ok, let's dig deeper: + +``` +❯ help set | grep -- -e + -e Exit immediately if a command exits with a non-zero status. +``` + +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: + +``` +❯ bash -c 'set -e; echo hello; grep -q bar <<< foo; echo bar' +hello +❯ echo $? +1 +``` + +Whereas the outcome changes when the regex matches: + +``` +❯ bash -c 'set -e; echo hello; grep -q bar <<< barman; echo bar' +hello +bar +❯ echo $? +0 +``` + +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: + +``` +❯ bash -c 'set -e +> grep -q bar <<< foo +> if [ $? -eq 0 ]; then +> echo "matching" +> else +> echo "not matching" +> fi' +❯ echo $? +1 +``` + +...but the example above won't reach any of the branches and won't print out anything, as the script terminates right after grep. + +The proper solution is to use grep as an expression in a conditional (e.g. in an if-else statement): + +``` +❯ bash -c 'set -e +> if grep -q bar <<< foo; then +> echo "matching" +> else +> echo "not matching" +> fi' +not matching +❯ echo $? +0 +❯ bash -c 'set -e +> if grep -q bar <<< barman; then +> echo "matching" +> else +> echo "not matching" +> fi' +matching +❯ echo $? +0 +``` + +You can also temporally undo "set -e" if there is no other way: + +``` +❯ cat ./e.sh +#!/usr/bin/env bash + +set -e + +foo () { + local arg="$1"; shift + + if [ -z "$arg" ]; then + arg='You!' + fi + echo "Hello $arg" +} + +bar () { + # Temporally disable e + set +e + local arg="$1"; shift + # Enable e again. + set -e + + if [ -z "$arg" ]; then + arg='You!' + fi + echo "Hello $arg" +} + +# Will succeed +bar World +foo Universe +bar + +# Will terminate the script +foo + +❯ ./e.sh +Hello World +Hello Universe +Hello You! +``` + +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. + +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 :-): + +[./2021-05-16-personal-bash-coding-style-guide.md](./2021-05-16-personal-bash-coding-style-guide.md) + +### pipefail + +The pipefail option makes it so that not only the exit code of the last command of the pipe counts regards its exit code but any command of the pipe: + +``` +❯ help set | grep pipefail -A 2 + 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 +``` + +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: + +``` +0 +❯ grep paul /etc/passwd | tr '[a-z]' '[A-Z]' +PAUL:X:1000:1000:PAUL BUETOW:/HOME/PAUL:/BIN/BASH +❯ echo $? +0 +``` + +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: + +``` +❯ grep TheRock /etc/passwd +❯ echo $? +1 +❯ grep TheRock /etc/passwd | tr '[a-z]' '[A-Z]' +❯ echo $? +0 +``` + +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: + +``` +❯ set -o pipefail +❯ grep TheRock /etc/passwd | tr '[a-z]' '[A-Z]' +❯ echo $? +1 +``` + +E-Mail me your thoughts at comments@mx.buetow.org! + +[Go back to the main site](../) diff --git a/gemfeed/2021-11-29-bash-golf-part-1.md b/gemfeed/2021-11-29-bash-golf-part-1.md new file mode 100644 index 00000000..c74bd031 --- /dev/null +++ b/gemfeed/2021-11-29-bash-golf-part-1.md @@ -0,0 +1,430 @@ +# Bash Golf Part 1 + +``` + + '\ . . |>18>> + \ . ' . | + O>> . 'o | + \ . | + /\ . | + / / .' | +jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Art by Joan Stark +``` + +> Published by Paul Buetow 2021-11-29 + +This is the first blog post about my Bash Golf series. This series is about 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. + +## TCP/IP networking + +You probably know the Netcat tool, which is a swiss army knife for TCP/IP networking on the command line. But did you know that the Bash natively supports TCP/IP networking? + +Have a look here how that works: + +``` +❯ cat < /dev/tcp/time.nist.gov/13 + +59536 21-11-18 08:09:16 00 0 0 153.6 UTC(NIST) * +``` + +The Bash treats /dev/tcp/HOST/PORT in a special way so that it is actually establishing a TCP connection to HOST:PORT. The example above redirects the TCP output of the time-server to cat and cat is printing it on standard output (stdout). + +A more sophisticated example is firing up an HTTP request. Let's create a new read-write (rw) file descriptor (fd) 5, redirect the HTTP request string to it, and then read the response back: + +``` +❯ exec 5<>/dev/tcp/google.de/80 +❯ echo -e "GET / HTTP/1.1\nhost: google.de\n\n" >&5 +❯ cat <&5 | head +HTTP/1.1 301 Moved Permanently +Location: http://www.google.de/ +Content-Type: text/html; charset=UTF-8 +Date: Thu, 18 Nov 2021 08:27:18 GMT +Expires: Sat, 18 Dec 2021 08:27:18 GMT +Cache-Control: public, max-age=2592000 +Server: gws +Content-Length: 218 +X-XSS-Protection: 0 +X-Frame-Options: SAMEORIGIN +``` + +You would assume that this also works with the ZSH, but it doesn't. This is one of the few things which don't work with the ZSH but in the Bash. There might be plugins you could use for ZSH to do something similar, though. + +## Process substitution + +The idea here is, that you can read the output (stdout) of a command from a file descriptor: + +``` +❯ uptime # Without process substitution + 10:58:03 up 4 days, 22:08, 1 user, load average: 0.16, 0.34, 0.41 + +❯ cat <(uptime) # With process substitution + 10:58:16 up 4 days, 22:08, 1 user, load average: 0.14, 0.33, 0.41 + +❯ stat <(uptime) + File: /dev/fd/63 -> pipe:[468130] + Size: 64 Blocks: 0 IO Block: 1024 symbolic link +Device: 16h/22d Inode: 468137 Links: 1 +Access: (0500/lr-x------) Uid: ( 1001/ paul) Gid: ( 1001/ paul) +Context: unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 +Access: 2021-11-20 10:59:31.482411961 +0000 +Modify: 2021-11-20 10:59:31.482411961 +0000 +Change: 2021-11-20 10:59:31.482411961 +0000 + Birth: - +``` + +This example doesn't make any sense practically speaking, but it clearly demonstrates how process substitution works. The standard output pipe of "uptime" is redirected to an anonymous file descriptor. That fd then is opened by the "cat" command as a regular file. + +A useful use case is displaying the differences of two sorted files: + +``` +❯ echo a > /tmp/file-a.txt +❯ echo b >> /tmp/file-a.txt +❯ echo c >> /tmp/file-a.txt +❯ echo b > /tmp/file-b.txt +❯ echo a >> /tmp/file-b.txt +❯ echo c >> /tmp/file-b.txt +❯ echo X >> /tmp/file-b.txt +❯ diff -u <(sort /tmp/file-a.txt) <(sort /tmp/file-b.txt) +--- /dev/fd/63 2021-11-20 11:05:03.667713554 +0000 ++++ /dev/fd/62 2021-11-20 11:05:03.667713554 +0000 +@@ -1,3 +1,4 @@ + a + b + c ++X +❯ echo X >> /tmp/file-a.txt # Now, both files have the same content again. +❯ diff -u <(sort /tmp/file-a.txt) <(sort /tmp/file-b.txt) +❯ +``` + +Another example is displaying the differences of two directories: + +``` +❯ diff -u <(ls ./dir1/ | sort) <(ls ./dir2/ | sort) +``` + +More (Bash golfing) examples: + +``` +❯ wc -l <(ls /tmp/) /etc/passwd <(env) + 24 /dev/fd/63 + 49 /etc/passwd + 24 /dev/fd/62 + 97 total +❯ + +❯ while read foo; do +> echo $foo +> done < <(echo foo bar baz) +foo bar baz +❯ +``` + +So far, we only used process substitution for stdout redirection. But it also works for stdin. The following two commands result into the same outcome, but the second one is writing the tar data stream to an anonymous file descriptor which is substituted by the "bzip2" command reading the data stream from stdin and compressing it to its own stdout, which then gets redirected to a file: + +``` +❯ tar cjf file.tar.bz2 foo +❯ tar cjf >(bzip2 -c > file.tar.bz2) foo +``` + +Just think a while and see whether you understand fully what is happening here. + +## Grouping + +Command grouping can be quite useful for combining the output of multiple commands: + +``` +❯ { ls /tmp; cat /etc/passwd; env; } | wc -l +97 +❯ ( ls /tmp; cat /etc/passwd; env; ) | wc -l +97 +``` + +But wait, what is the difference between curly braces and normal braces? I assumed that the normal braces create a subprocess whereas the curly ones don't, but I was wrong: + +``` +❯ echo $$ +62676 +❯ { echo $$; } +62676 +❯ ( echo $$; ) +62676 +``` + +One difference is, that the curly braces require you to end the last statement with a semicolon, whereas with the normal braces you can omit the last semicolon: + +``` +❯ ( env; ls ) | wc -l +27 +❯ { env; ls } | wc -l +> +> ^C +``` + +In case you know more (subtle) differences, please write me an E-Mail and let me know. + +## Expansions + +Let's start with simple examples: + +``` +❯ echo {0..5} +0 1 2 3 4 5 +❯ for i in {0..5}; do echo $i; done +0 +1 +2 +3 +4 +5 +``` + +You can also add leading 0 or expand to any number range: + +``` +❯ echo {00..05} +00 01 02 03 04 05 +❯ echo {000..005} +000 001 002 003 004 005 +❯ echo {201..205} +201 202 203 204 205 +``` + +It also works with letters: + +``` +❯ echo {a..e} +a b c d e +``` + +Now it gets interesting. The following takes a list of words and expands it so that all words are quoted: + +``` +❯ echo \"{These,words,are,quoted}\" +"These" "words" "are" "quoted" +``` + +Let's also expand to the cross product of two given lists: + +``` +❯ echo {one,two}\:{A,B,C} +one:A one:B one:C two:A two:B two:C +❯ echo \"{one,two}\:{A,B,C}\" +"one:A" "one:B" "one:C" "two:A" "two:B" "two:C" +``` + +Just because we can: + +``` +❯ echo Linux-{one,two,three}\:{A,B,C}-FreeBSD +Linux-one:A-FreeBSD Linux-one:B-FreeBSD Linux-one:C-FreeBSD Linux-two:A-FreeBSD Linux-two:B-FreeBSD Linux-two:C-FreeBSD Linux-three:A-FreeBSD Linux-three:B-FreeBSD Linux-three:C-FreeBSD +``` + +## - aka stdin and stdout placeholder + +Some commands and Bash builtins use "-" as a placeholder for stdin and stdout: + +``` +❯ echo Hello world +Hello world +❯ echo Hello world | cat - +Hello world +❯ cat - <<ONECHEESEBURGERPLEASE +Hello world +ONECHEESEBURGERPLEASE +Hello world +❯ cat - <<< 'Hello world' +Hello world +``` + +Let's walk through all three examples from the above snippet: + +* The first example is obvious (the Bash builtin "echo" prints its arguments to stdout). +* The second pipes "Hello world" via stdout to stdin of the "cat" command. As cat's argument is "-" it reads its data from stdin and not from a regular file named "-". So "-" has a special meaning for cat. +* The third and fourth examples are interesting as we don't use a pipe as of "|" but a so-called HERE-document and a HERE-string. But the end results are the same. + +The "tar" command understands "-" too. The following example tars up some local directory and sends the data to stdout (this is what "-f -" commands it to do). stdout then is piped via an SSH session to a remote tar process (running on snonux.de) and reads the data from stdin and extracts all the data coming from stdin (as we told tar with "-f -") on the remote machine: + +``` +❯ tar -czf - /some/dir | ssh hercules@snonux.de tar -xzvf - +``` + +This is yet another example of using "-", but this time using the "file" command: + +``` +$ head -n 1 grandmaster.sh +#!/usr/bin/env bash +$ file - < <(head -n 1 grandmaster.sh) +/dev/stdin: a /usr/bin/env bash script, ASCII text executable +``` + +Some more golfing: + +``` +$ cat - +hello +hello +^C +$ file - +#!/usr/bin/perl +/dev/stdin: Perl script text executable +``` + +## Alternative argument passing + +This is a quite unusual way of passing arguments to a Bash script: + +``` +❯ cat foo.sh +#/usr/bin/env bash +declare -r USER=${USER:?Missing the username} +declare -r PASS=${PASS:?Missing the secret password for $USER} +echo $USER:$PASS +``` + +So what we are doing here is to pass the arguments via environment variables to the script. The script will abort with an error when there's an undefined argument. + +``` +❯ chmod +x foo.sh +❯ ./foo.sh +./foo.sh: line 3: USER: Missing the username +❯ USER=paul ./foo.sh +./foo.sh: line 4: PASS: Missing the secret password for paul +❯ echo $? +1 +❯ USER=paul PASS=secret ./foo.sh +paul:secret +``` + +You have probably noticed this *strange* syntax: + +``` +❯ VARIABLE1=value1 VARIABLE2=value2 ./script.sh +``` + +That's just another way to pass environment variables to a script. You can write it as well as like this: + +``` +❯ export VARIABLE1=value1 +❯ export VARIABLE2=value2 +❯ ./script.sh +``` + +But the downside of it is that the variables will also be defined in your current shell environment and not just in the scripts sub-process. + +## : aka the null command + +First, let's use the "help" Bash built-in to see what it says about the null command: + +``` +❯ help : +:: : + Null command. + + No effect; the command does nothing. + + Exit Status: + Always succeeds. +``` + +PS: IMHO, people should use the Bash help more often. It is a very useful Bash reference. Too many fallbacks to a Google search and then land on Stack Overflow. Sadly, there's no help built-in for the ZSH shell though (so even when I am using the ZSH I make use of the Bash help as most of the built-ins are compatible). + +OK, back to the null command. What happens when you try to run it? As you can see, absolutely nothing. And its exit status is 0 (success): + +``` +❯ : +❯ echo $? +0 +``` + +Why would that be useful? You can use it as a placeholder in an endless while-loop: + +``` +❯ while : ; do date; sleep 1; done +Sun 21 Nov 12:08:31 GMT 2021 +Sun 21 Nov 12:08:32 GMT 2021 +Sun 21 Nov 12:08:33 GMT 2021 +^C +❯ +``` + +You can also use it as a placeholder for a function body not yet fully implemented, as an empty function ill result in a syntax error: + +``` +❯ foo () { } +-bash: syntax error near unexpected token `}' +❯ foo () { :; } +❯ foo +❯ +``` + +Or use it as a placeholder for not yet implemented conditional branches: + +``` +❯ if foo; then :; else echo bar; fi +``` + +Or (not recommended) as a fancy way to comment your Bash code: + +``` +❯ : I am a comment and have no other effect +❯ : I am a comment and result in a syntax error () +-bash: syntax error near unexpected token `(' +❯ : "I am a comment and don't result in a syntax error ()" +❯ +``` + +As you can see in the previous example, the Bash still tries to interpret some syntax of all text following after ":". This can be exploited (also not recommended) like this: + +``` +❯ declare i=0 +❯ $[ i = i + 1 ] +bash: 1: command not found... +❯ : $[ i = i + 1 ] +❯ : $[ i = i + 1 ] +❯ : $[ i = i + 1 ] +❯ echo $i +4 +``` + +For these kinds of expressions it's always better to use "let" though. And you should also use $((...expression...)) instead of the old (deprecated) way $[ ...expression... ] like this example demonstrates: + +``` +❯ declare j=0 +❯ let i=$((j + 1)) +❯ let i=$((j + 1)) +❯ let i=$((j + 1)) +❯ let i=$((j + 1)) +❯ echo $j +4 +``` + +## (No) floating point support + +I have to give a plus-point to the ZSH here. As the ZSH supports floating point calculation, whereas the Bash doesn't: + +``` +❯ bash -c 'echo $(( 1/10 ))' +0 +❯ zsh -c 'echo $(( 1/10 ))' +0 +❯ bash -c 'echo $(( 1/10.0 ))' +bash: line 1: 1/10.0 : syntax error: invalid arithmetic operator (error token is ".0 ") +❯ zsh -c 'echo $(( 1/10.0 ))' +0.10000000000000001 +❯ +``` + +It would be nice to have native floating point support for the Bash too, but you don't want to use the shell for complicated calculations anyway. So it's fine that Bash doesn't have that, I guess. + +In the Bash you will have to fall back to an external command like "bc" (the arbitrary precision calculator language): + +``` +❯ bc <<< 'scale=2; 1/10' +.10 +``` + +See you later for the next post of this series. E-Mail me your thoughts at comments@mx.buetow.org! + +[Go back to the main site](../) diff --git a/gemfeed/index.md b/gemfeed/index.md index b8023a16..9be6b37a 100644 --- a/gemfeed/index.md +++ b/gemfeed/index.md @@ -2,6 +2,7 @@ ## Having fun with computers! +[2021-11-29 (1182 words) - Bash Golf Part 1](./2021-11-29-bash-golf-part-1.md) [2021-10-22 (2276 words) - Defensive DevOps](./2021-10-22-defensive-devops.md) [2021-09-12 (1365 words) - Keep it simple and stupid](./2021-09-12-keep-it-simple-and-stupid.md) [2021-08-01 (2919 words) - On being Pedantic about Open-Source](./2021-08-01-on-being-pedantic-about-open-source.md) |
