r/linux4noobs • • Sep 22 '18

Piping vs. command substitution--what's the difference?

What's the difference between command substitution vs. piping? See the reply to the thread here where command substitution works and piping doesn't.

On an unrelated note, how can I parse the data from https://freegeoip.app/ and https://ipdata.co/ as described in that thread?

Much appreciated.

5 Upvotes

3 comments sorted by

11

u/AiwendilH Sep 22 '18 edited Sep 22 '18

Piping redirects the output of one program to the input of another program.

Command substitution changes the command you enter by replacing the part with the command substitution with the output of the program.

Piping only works if the other program reads input from stdin (standard input channel).

Command substitution only works if the other program allows being called with an argument that can be fulfilled by the command substitution output.

example:

$ echo hello | cat
hello

works because cat reads from stdin by default so cat just displays what it reads from there...the output of echo

$ cat $(echo hello)
cat: hello: No such file or directory

Doesn't work because the result of command subsitution is cat hello...what cat interprets as a filename to use.

Or the other way around...lets asume we have a test.txt file...

$ echo test.txt | cat
test.txt

Well..kind of works but probably not what you wanted...it outputs what you gave with echo..

$ cat $(echo test.txt)
<outputs the content of the test.txt file>

I hope that makes it more clear now.

1

u/Terewawa Sep 03 '23

If the program would not read stdin you can always trick it by turning stdin into an argument using process substitution. So it would work on pretty much any program.

1

u/lutusp Sep 22 '18

What's the difference between command substitution vs. piping?

They're two ways to get the same result. Using pipes is generally more flexible and easier to understand. Once you understand how they work, you will realize they're just variations on a theme.

On an unrelated note, how can I parse the data from https://freegeoip.app/ and https://ipdata.co/ as described in that thread?

By writing a script, possibly in Bash's shell language, but preferably in Python.