Bash offers several powerful features to simplify your command-line interactions. Two of these features are process substitution and shell history expansions.
Process Substitution
—————–
Process substitution allows you to create a temporary file path from a command output. This can be useful when you need to pipe data into an external program but lack the file path as an argument.
To demonstrate this, let’s take the example of editing text in the terminal. The previous command does not work because you cannot pipe data into nano; instead, you need to provide a file path. Process substitution resolves this issue by creating a temporary file and providing its path.
Here’s how it works:
“`bash
echo <(true)
```
This command creates a temporary file and prints the file descriptor as output. You can then use this file descriptor to specify the file path in nano or any other program.
Example usage:
```bash
nano <(echo "foo")
```
Output: `/dev/fd/16`
Input/Output Process Substitution
--------------------------------
Process substitution comes in two forms: input and output. The "<(command)" expression creates an input process substitution, while the "> (command)” expression creates an output process substitution.
The output process substitution is useful when you want to capture the output of a command and use it as input for another command.
Example usage:
“`bash
echo “foo” > >(cat)
“`
This command writes “foo” to a special file, which is then read by the cat command.
History Expansion
—————–
Shell history expansions allow you to expand simple character inputs into items in your shell history. There are several types of history expansions:
* **Bang expansion**: Re-runs the last executed command.
* **Tilde expansion**: Expands to a path for your home directory.
* **Fuzzy search and expansion**: Allows you to partially type a command and execute the most recent match.
Example usage:
“`bash
!! # re-run the last command
!10 # re-run the 10th command in history
“`
You can also use these expansions to expand specific items in your history. For example, to expand item number 5:
“`bash
!5
“`
Command Groups
————-
A command group is a way to execute multiple commands as a single unit and treat their output as one result.
Example usage:
“`bash
{ echo foo; echo bar; } > /tmp/foo.txt
“`
This will create a file with the contents of both “foo” and “bar”.
In summary, Bash offers several powerful features to simplify your command-line interactions. Process substitution allows you to create temporary files, while shell history expansions provide a way to expand simple character inputs into items in your history.
Source: https://www.howtogeek.com/terminal-tricks-youll-wish-you-knew-earlier