0

I was wondering if this way of getting the first element from the $PATH variable is the most optimal and preferred choice on a very large script which needs to be as fast as possible.

echo $PATH | awk  -F ":" '{print $1}'

This successfully returns /usr/local/sbin

  • But is there any way of making that line of code faster? Thanks
  • 1
    It's slow _because you use awk_ – Charles Duffy Jul 20 '21 at 17:14
  • 2
    `firstPathEntry=${PATH%%:*}` would be much, much faster, because it's using only features built into the shell. No external commands (which require a `fork()` and `execve()` -- the latter of which involves firing up the OS's dynamic linker and a bunch of other mechanisms that would otherwise be uninvolved), no pipelines (which similarly add a `fork()`), etc. – Charles Duffy Jul 20 '21 at 17:14
  • 1
    Anyhow, "any way of making that line of code faster" is ambiguous. Do you mean faster _while still using awk_? If you just want an efficient way to get everything before the first `:` in a variable, your question's title should ask that, instead of being titled "running awk on...", thus implying only an answer that still uses awk is acceptable. – Charles Duffy Jul 20 '21 at 17:15
  • To be clear, awk is typically faster than native bash, but that's true _only after you've cleared the time needed to start it up_. Thus, it's reasonable to start up awk to run it over a large stream of input (so the process startup costs get amortized); not so much, when the input is just one line. – Charles Duffy Jul 20 '21 at 17:18
  • Many thanks @CharlesDuffy people like you make the learning path to Linux more enjoyable. – pullhyphoonprotocol Jul 20 '21 at 17:20

0 Answers0