domi,
@domi@donotsta.re avatar

It’s again!

Being on the internet (which, I think you are right now - sorry to break the news to you :neocat_hug:), you’ve probably heard the term “cat abuse” from some reply guy. Usually it boils down to something like this:

cat a | grep meow

cat, and, by extension, the pipe, are redundant here because grep can just read a file. There are certain arguments for, and against this (i.e. when editing a regexp, it may make sense to do cat abuse, as you don’t have to scroll through the filename with each iteration); But this is not what I call cat abuse. There’s one way that’s even more cursed, but also makes some sense to use in a script.

Have you ever wanted to filter a file and send the output back into the same file, with no intermediates? Or maybe prepend a 2nd file to your first one, without creating a mess? Try this:

cat <<< "$(cat "$subtemplate" "$tmp")"" > "$tmp" 

This is taken from HTTP.sh, the templating engine to be precise. That file is kind of cursed and not necessarily good code in general, but this line is special and i’ve been reusing it in a bunch of places.

Bash pipes and redirects have a few levels of precedence. By default, if you execute cat b a > a, the a file gets overwritten before it can be read. Instead, we use a subshell in a herestring (although a herestring is not strictly necessary for this trick). A subshell always takes precedence before the redirect, thus our file can be read and written in a single command chain!

Another neat oddity is that pipes act very similarly to subshells! Similarly, that “cat abuse” from before could be rewritten to a somewhat simpler form:

cat b a | tee a
# works like you'd expect!

On the contrary, you might have noticed that it’s impossible to set a variable in a pipe chain and read it back later:

$ echo meow | read n
$ declare -p n
bash: declare: n: not found

Now, this can be solved by using a herestring! Just restructure it like so:

$ read n <<< "$(echo meow)"
$ declare -p n
declare -- n="meow"

All this can be slightly confusing, but I hope this post made it a bit simpler :blobcatheart:

  • All
  • Subscribed
  • Moderated
  • Favorites
  • random
  • kavyap
  • mdbf
  • tacticalgear
  • osvaldo12
  • InstantRegret
  • DreamBathrooms
  • cubers
  • magazineikmin
  • thenastyranch
  • khanakhh
  • Youngstown
  • slotface
  • rosin
  • ethstaker
  • JUstTest
  • tester
  • GTA5RPClips
  • Durango
  • modclub
  • Leos
  • ngwrru68w68
  • everett
  • anitta
  • cisconetworking
  • provamag3
  • normalnudes
  • megavids
  • lostlight
  • All magazines