Home | Notes | Github |
---|
Written: 05-Mar-2022
Chaining commands is where shell becomes very handy. This is particularly useful for doing stuff on a single line - called one liners cleverly - on the console. There are several techniques for this, and best explained with an example: cmd1
operator
cmd2
Replacing operator
with the following yields different results.
;
- Simple chain - do cmd1
then do cmd2
.&&
- AND - do cmd1
and if successful do cmd2
.||
- OR - do cmd1
and if unsuccessful do cmd2
.|
- Pipe - do cmd1
and input the results to cmd2
&&
and ;
are pretty similar, however if cmd1
returns an error then with &&
the next command won’t run. Geeks for geeks has more info (as always).
The first three are pretty obvious, however piping - |
- is very tasty. The functionality allows the output of one command to be the input of another. A simple example of this would be:
ls | grep ".py"
Which would find any python files in the current directory.
As an aside piping ls
into grep
isn’t ideal1 and find
should be used instead (but I’ve done it many times, just don’t let anyone see 🙈). An example I’ve used recently is:
find . -iregex '.*\.jpg' | fim -
This searches for jpeg
images in the current folder using find
(ignoring all the arguments etc.) and them passes them to fim
to view. Notably the -
is what tells fim
to look for input from something else, but not all programs require it (like grep
above). Look at the man
page for help here.
The mechanism of how this works is called standard streams (you may hear of stdin
and stdout
) but it’s not required info for a quick and dirty understanding.
Terminal Tut 1 - Meta Commands
Its bad because shellcheck
will highlight it in scripts and tell you off. No-one wants to be told off by shellcheck
.↩︎