Understanding Linux Redirects and Related Commands
Linux provides powerful tools for redirecting input and output, allowing you to control where data goes and comes from. Here are some of the most commonly used redirection operators and commands:1. Standard Output (> and >>)
- >: Redirects standard output to a file, overwriting the file if it exists.
Code:echo "Hello, World!" > output.txt
- >>: Appends standard output to a file, preserving the existing content.
Code:echo "Hello again!" >> output.txt
2. Standard Input (<)
- <: Redirects standard input from a file.
Code:
cat < input.txt
3. Pipe (|)
- |: Passes the output of one command as input to another command.
Code:
ls -l | grep "txt"
4. Background Execution (&)
- &: Runs a command in the background.
Code:
sleep 60 &
5. Logical AND (&&)
- &&: Executes the second command only if the first command succeeds.
Code:
mkdir new_directory && cd new_directory
6. nohup
- nohup: Runs a command immune to hangups, with output redirected to nohup.out by default.
Code:
nohup long_running_command &
7. Standard Output and Error (stdout and stderr)
- stdout: Standard output, usually the terminal.
- stderr: Standard error, used for error messages.
Code:
command > output.txt 2>&1
Or redirect them separately:
Code:
command > stdout.txt 2> stderr.txt