Files
the_information_nexus/tech_docs/linux/shell_scripting.md
2024-05-01 12:28:44 -06:00

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, and case statements to control the flow of execution based on conditions.
    • The [[ ]] construct offers more flexibility and is recommended over [ ] for test operations.
  • Loops:

    • for loops are used to iterate over a list of items.
    • while and until loops execute commands as long as the test condition is true (or false for until).
    • Example: for file in *; do echo "$file"; done
  • Functions: Define reusable code blocks. Syntax: myfunc() { command1; command2; }. Call it by simply using myfunc.

  • Script Debugging: Utilize set -x to print each command before execution, set -e to exit on error, and set -u to 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}.txt creates file1.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.
    • tee reads from standard input and writes to standard output and files, useful for viewing and logging simultaneously.

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.