eolas/zk/Redirection.md

50 lines
1.1 KiB
Markdown
Raw Normal View History

2022-04-23 13:26:53 +01:00
---
tags:
- shell
---
2022-12-11 15:00:04 +00:00
# Redirection
2022-04-23 13:26:53 +01:00
2022-12-11 18:30:05 +00:00
## Redirecting outputs
2023-01-26 16:02:11 +00:00
The symbol `>` is called the **redirection operator** because it redirects
`stdout` to another program or file. You most frequently use this when you want
to save contents to a file rather than standard output.
2022-04-23 13:26:53 +01:00
2022-09-06 15:44:40 +01:00
```bash
2022-12-11 15:00:04 +00:00
ls | grep d* > result.txt
2022-09-06 15:44:40 +01:00
```
2022-04-23 13:26:53 +01:00
2023-01-31 13:55:42 +00:00
### Combining redirection with file escriptors
2022-12-11 18:30:05 +00:00
It is common practice to combine redirection with the
2024-02-17 11:57:44 +00:00
[file descriptors](File_descriptors.md) to redirect
the output of `stdout` and `stderr`. A common case is to
2024-02-17 11:57:44 +00:00
[redirect error output to `/dev/null`](Redirect_to_dev_null.md).
2022-12-11 18:30:05 +00:00
2023-01-26 16:02:11 +00:00
Redirection defaults to interpreting `>` as the redirection of `stdout` (`1`);
2022-12-11 18:30:05 +00:00
## Redirecting inputs
We can also switch the direction of the redirection symbol and pass in a file to
a command rather than command ouput to a file:
2022-12-11 19:00:05 +00:00
```bash
sql-processing-program < data.sql
```
2023-01-26 16:02:11 +00:00
We can redirect a string with three carets:
```bash
program <<< "this is a string input"
```
## Appending
2022-04-23 13:26:53 +01:00
We use `>>` to append contents on the next available line of a pre-existing
file. Continuing on from the example above:
2022-04-23 13:26:53 +01:00
2022-09-06 15:44:40 +01:00
```bash
2022-04-23 13:26:53 +01:00
echo 'These are the files I just grepped' >> result.txt
2022-09-06 15:44:40 +01:00
```