2.8 KiB
1. Bash Startup Files
Understanding Bash startup files is crucial for setting up your environment effectively:
~/.bash_profile,~/.bash_login, and~/.profile: These files are read and executed by Bash for login shells. Here, you can set environment variables, and startup programs, and customize user environments that should be applied once at login.~/.bashrc: For non-login shells (e.g., opening a new terminal window), Bash reads this file. It's the place to define aliases, functions, and shell options that you want to be available in all your sessions.
2. Shell Scripting
A foundational understanding of scripting basics enhances the automation and functionality of tasks:
-
Variables and Quoting: Use variables to store data and quotations to handle strings containing spaces or special characters. Always quote your variables (
"$variable") to avoid unintended splitting and globbing. -
Conditional Execution:
- Use
if,else,elif, andcasestatements to control the flow of execution based on conditions. - The
[[ ]]construct offers more flexibility and is recommended over[ ]for test operations.
- Use
-
Loops:
forloops are used to iterate over a list of items.whileanduntilloops execute commands as long as the test condition is true (or false foruntil).- Example:
for file in *; do echo "$file"; done
-
Functions: Define reusable code blocks. Syntax:
myfunc() { command1; command2; }. Call it by simply usingmyfunc. -
Script Debugging: Utilize
set -xto print each command before execution,set -eto exit on error, andset -uto treat unset variables as an error.
3. Advanced Command Line Tricks
Enhance your command-line efficiency with these advanced techniques:
-
Brace Expansion: Generates arbitrary strings, e.g.,
file{1,2,3}.txtcreatesfile1.txt file2.txt file3.txt. -
Command Substitution: Capture the output of a command for use as input in another command using
$(command)syntax. Example:echo "Today is $(date)". -
Process Substitution: Treats the input or output of a command as if it were a file using
<()and>(). Example:diff <(command1) <(command2)compares the output of two commands. -
Redirection and Pipes:
- Redirect output using
>for overwrite or>>for append. - Use
<to redirect input from a file. - Pipe
|connects the output of one command to the input of another. teereads from standard input and writes to standard output and files, useful for viewing and logging simultaneously.
- Redirect output using
This cheatsheet provides a concise overview of essential Bash scripting and command-line techniques, serving as a quick reference for advanced CLI users to enhance their productivity and scripting capabilities on Linux and macOS systems.