Command line operators
Command line operators are special characters that help you control how commands work and interact with each other. Think of them as the "glue" that connects different commands or directs where information should go. These operators solve common problems, such as saving command output to a file, running multiple commands in sequence, or using the output of one command as input for another.
Without operators, you would have to manually copy and paste outputs between commands or run each command separately, checking if it succeeded before running the next one. Operators make your workflow more efficient and help automate repetitive tasks.
Redirection operators (>
, >>
)
Redirection operators take the output of a command and send it to a file or another destination, instead of displaying it on the screen. This is useful for saving command results or logs.
Here's a mnemonic to remember the difference:
>
: 1 arrow = keep 1 thing = keep mine>>
: 2 arrows = keep 2 things = keep yours and mine
Write a piece of text to a file:
echo "Hello, World!" > hello.txt
Append the last 5 commits to a changelog file:
git log -5 --oneline >> CHANGELOG.md
Pipe operator (|
)
The pipe operator takes the output from one command and uses it as input for another command. This creates a "pipeline," where data flows from one command to the next, like water through connected pipes.
Select commits that contain the word "fix" in their message:
Linux/macOS:
git log --oneline | grep "fix" | sort
PowerShell:
git log --oneline | Select-String "fix" | Sort-Object
Logical operators (&&
, ||
)
Logical operators, similar to those in programming languages, control the flow of command execution based on the success or failure of previous commands.
&&
: Runs the next command only if the previous command succeeded (exit code 0).||
: Runs the next command only if the previous command failed (non-zero exit code).
Add files and commit only if adding succeeds:
git add . && git commit -m "Update documentation"
Try to pull; if it fails, then just fetch:
git pull origin main || git fetch origin