diff options
Diffstat (limited to 'gemfeed/2021-11-29-bash-golf-part-1.html')
| -rw-r--r-- | gemfeed/2021-11-29-bash-golf-part-1.html | 78 |
1 files changed, 39 insertions, 39 deletions
diff --git a/gemfeed/2021-11-29-bash-golf-part-1.html b/gemfeed/2021-11-29-bash-golf-part-1.html index 5aae4576..fb392e0e 100644 --- a/gemfeed/2021-11-29-bash-golf-part-1.html +++ b/gemfeed/2021-11-29-bash-golf-part-1.html @@ -19,10 +19,10 @@ / / .' | jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Art by Joan Stark -</pre> +</pre><br /> <p class="quote"><i>Published by Paul at 2021-11-29, last updated at 2022-01-05</i></p> <p>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.</p> -<a class="textlink" href="./2021-11-29-bash-golf-part-1.html">Bash Golf Part 1 (you are reding this atm.)</a><br /> +<a class="textlink" href="./2021-11-29-bash-golf-part-1.html">Bash Golf Part 1 (you are reading this atm.)</a><br /> <a class="textlink" href="./2022-01-01-bash-golf-part-2.html">Bash Golf Part 2</a><br /> <h2>TCP/IP networking</h2> <p>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?</p> @@ -31,7 +31,7 @@ jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ❯ cat < /dev/tcp/time.nist.gov/13 59536 21-11-18 08:09:16 00 0 0 153.6 UTC(NIST) * -</pre> +</pre><br /> <p>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).</p> <p>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:</p> <pre> @@ -48,7 +48,7 @@ Server: gws Content-Length: 218 X-XSS-Protection: 0 X-Frame-Options: SAMEORIGIN -</pre> +</pre><br /> <p>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.</p> <h2>Process substitution</h2> <p>The idea here is, that you can read the output (stdout) of a command from a file descriptor:</p> @@ -69,7 +69,7 @@ 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: - -</pre> +</pre><br /> <p>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.</p> <p>A useful use case is displaying the differences of two sorted files:</p> <pre> @@ -91,11 +91,11 @@ Change: 2021-11-20 10:59:31.482411961 +0000 ❯ 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) ❯ -</pre> +</pre><br /> <p>Another example is displaying the differences of two directories:</p> <pre> ❯ diff -u <(ls ./dir1/ | sort) <(ls ./dir2/ | sort) -</pre> +</pre><br /> <p>More (Bash golfing) examples:</p> <pre> ❯ wc -l <(ls /tmp/) /etc/passwd <(env) @@ -110,12 +110,12 @@ Change: 2021-11-20 10:59:31.482411961 +0000 > done < <(echo foo bar baz) foo bar baz ❯ -</pre> +</pre><br /> <p>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:</p> <pre> ❯ tar cjf file.tar.bz2 foo ❯ tar cjf >(bzip2 -c > file.tar.bz2) foo -</pre> +</pre><br /> <p>Just think a while and see whether you understand fully what is happening here.</p> <h2>Grouping</h2> <p>Command grouping can be quite useful for combining the output of multiple commands:</p> @@ -124,7 +124,7 @@ foo bar baz 97 ❯ ( ls /tmp; cat /etc/passwd; env; ) | wc -l 97 -</pre> +</pre><br /> <p>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:</p> <pre> ❯ echo $$ @@ -133,7 +133,7 @@ foo bar baz 62676 ❯ ( echo $$; ) 62676 -</pre> +</pre><br /> <p>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:</p> <pre> ❯ ( env; ls ) | wc -l @@ -141,7 +141,7 @@ foo bar baz ❯ { env; ls } | wc -l > > ^C -</pre> +</pre><br /> <p>In case you know more (subtle) differences, please write me an E-Mail and let me know.</p> <p class="quote"><i>Update: A reader sent me an E-Mail and pointed me to the Bash manual page, which explains the difference between () and {} (I should have checked that by myself):</i></p> <pre> @@ -157,19 +157,19 @@ foo bar baz ters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized. Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharacter. -</pre> +</pre><br /> <p>So I was right that () is executed in a subprocess. But why does $$ not show a different PID? Also here (as pointed out by the reader) is the answer in the manual page:</p> <pre> $ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell. -</pre> +</pre><br /> <p>If we want print the subprocess PID, we can use the BASHPID variable:</p> <pre> ❯ echo $BASHPID; { echo $BASHPID; }; ( echo $BASHPID; ) 1028465 1028465 1028739 -</pre> +</pre><br /> <h2>Expansions</h2> <p>Let's start with simple examples:</p> <pre> @@ -182,7 +182,7 @@ $ Expands to the process ID of the shell. In a () subshell, it expands to 3 4 5 -</pre> +</pre><br /> <p>You can also add leading 0 or expand to any number range:</p> <pre> ❯ echo {00..05} @@ -191,29 +191,29 @@ $ Expands to the process ID of the shell. In a () subshell, it expands to 000 001 002 003 004 005 ❯ echo {201..205} 201 202 203 204 205 -</pre> +</pre><br /> <p>It also works with letters:</p> <pre> ❯ echo {a..e} a b c d e -</pre> +</pre><br /> <p>Now it gets interesting. The following takes a list of words and expands it so that all words are quoted:</p> <pre> ❯ echo \"{These,words,are,quoted}\" "These" "words" "are" "quoted" -</pre> +</pre><br /> <p>Let's also expand to the cross product of two given lists:</p> <pre> ❯ 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" -</pre> +</pre><br /> <p>Just because we can:</p> <pre> ❯ 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 -</pre> +</pre><br /> <h2>- aka stdin and stdout placeholder</h2> <p>Some commands and Bash builtins use "-" as a placeholder for stdin and stdout:</p> <pre> @@ -227,7 +227,7 @@ ONECHEESEBURGERPLEASE Hello world ❯ cat - <<< 'Hello world' Hello world -</pre> +</pre><br /> <p>Let's walk through all three examples from the above snippet:</p> <ul> <li>The first example is obvious (the Bash builtin "echo" prints its arguments to stdout).</li> @@ -237,14 +237,14 @@ Hello world <p>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 buetow.org) and reads the data from stdin and extracts all the data coming from stdin (as we told tar with "-f -") on the remote machine:</p> <pre> ❯ tar -czf - /some/dir | ssh hercules@buetow.org tar -xzvf - -</pre> +</pre><br /> <p>This is yet another example of using "-", but this time using the "file" command:</p> <pre> $ 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 -</pre> +</pre><br /> <p>Some more golfing:</p> <pre> $ cat - @@ -254,7 +254,7 @@ hello $ file - #!/usr/bin/perl /dev/stdin: Perl script text executable -</pre> +</pre><br /> <h2>Alternative argument passing</h2> <p>This is a quite unusual way of passing arguments to a Bash script:</p> <pre> @@ -263,7 +263,7 @@ $ file - declare -r USER=${USER:?Missing the username} declare -r PASS=${PASS:?Missing the secret password for $USER} echo $USER:$PASS -</pre> +</pre><br /> <p>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.</p> <pre> ❯ chmod +x foo.sh @@ -275,17 +275,17 @@ echo $USER:$PASS 1 ❯ USER=paul PASS=secret ./foo.sh paul:secret -</pre> +</pre><br /> <p>You have probably noticed this *strange* syntax:</p> <pre> ❯ VARIABLE1=value1 VARIABLE2=value2 ./script.sh -</pre> +</pre><br /> <p>That's just another way to pass environment variables to a script. You can write it as well as like this:</p> <pre> ❯ export VARIABLE1=value1 ❯ export VARIABLE2=value2 ❯ ./script.sh -</pre> +</pre><br /> <p>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.</p> <h2>: aka the null command</h2> <p>First, let's use the "help" Bash built-in to see what it says about the null command:</p> @@ -298,14 +298,14 @@ paul:secret Exit Status: Always succeeds. -</pre> +</pre><br /> <p>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). </p> <p>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):</p> <pre> ❯ : ❯ echo $? 0 -</pre> +</pre><br /> <p>Why would that be useful? You can use it as a placeholder in an endless while-loop:</p> <pre> ❯ while : ; do date; sleep 1; done @@ -314,7 +314,7 @@ Sun 21 Nov 12:08:32 GMT 2021 Sun 21 Nov 12:08:33 GMT 2021 ^C ❯ -</pre> +</pre><br /> <p>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:</p> <pre> ❯ foo () { } @@ -322,11 +322,11 @@ Sun 21 Nov 12:08:33 GMT 2021 ❯ foo () { :; } ❯ foo ❯ -</pre> +</pre><br /> <p>Or use it as a placeholder for not yet implemented conditional branches:</p> <pre> ❯ if foo; then :; else echo bar; fi -</pre> +</pre><br /> <p>Or (not recommended) as a fancy way to comment your Bash code:</p> <pre> ❯ : I am a comment and have no other effect @@ -334,7 +334,7 @@ Sun 21 Nov 12:08:33 GMT 2021 -bash: syntax error near unexpected token `(' ❯ : "I am a comment and don't result in a syntax error ()" ❯ -</pre> +</pre><br /> <p>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:</p> <pre> ❯ declare i=0 @@ -345,7 +345,7 @@ bash: 1: command not found... ❯ : $[ i = i + 1 ] ❯ echo $i 4 -</pre> +</pre><br /> <p>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:</p> <pre> ❯ declare j=0 @@ -355,7 +355,7 @@ bash: 1: command not found... ❯ let j=$((j + 1)) ❯ echo $j 4 -</pre> +</pre><br /> <h2>(No) floating point support</h2> <p>I have to give a plus-point to the ZSH here. As the ZSH supports floating point calculation, whereas the Bash doesn't:</p> <pre> @@ -368,13 +368,13 @@ bash: line 1: 1/10.0 : syntax error: invalid arithmetic operator (error token is ❯ zsh -c 'echo $(( 1/10.0 ))' 0.10000000000000001 ❯ -</pre> +</pre><br /> <p>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. </p> <p>In the Bash you will have to fall back to an external command like "bc" (the arbitrary precision calculator language):</p> <pre> ❯ bc <<< 'scale=2; 1/10' .10 -</pre> +</pre><br /> <p>See you later for the next post of this series. 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"> |
