Document Details

LuxuryAbundance

Uploaded by LuxuryAbundance

Algonquin College

Tags

shell scripting command line Unix programming

Full Transcript

**Week 9** **Shell Variables** 1. **Shell Variables (\$foo and \${foo}):** - Variables in shell scripts store text or numeric values. - Assign values using = without spaces around it. - Examples: - Use \$ to expand variables in commands or scripts. 2. **Quoting to Preven...

**Week 9** **Shell Variables** 1. **Shell Variables (\$foo and \${foo}):** - Variables in shell scripts store text or numeric values. - Assign values using = without spaces around it. - Examples: - Use \$ to expand variables in commands or scripts. 2. **Quoting to Prevent Variable Expansion:** - Use single quotes or backslashes to prevent immediate variable expansion. - Example: 3. **Double-Quote All Uses of Variables:** - Always double-quote variables to prevent word-splitting and GLOB expansion. - Example: 4. **Unrecognized Variables Are Empty:** - Undefined variables expand to nothing unless nounset option is set. - Example: 5. **Appending to Variables:** - Append to a variable using \$VARNAME=\$VARNAME:newtext. - Example: 6. **Local vs Environment (Global) Variables:** - Local variables are specific to the current shell. - Exported (environment) variables are inherited by child processes. - Example: 7. **Pre-set Environment Variables:** - Examples of common environment variables: \$PATH, \$USER, \$HOME, \$SHELL, \$TERM, \$\$. 8. **Variable Best Practices:** - Use descriptive names. - Always quote variable expansions unless you specifically want word-splitting or GLOB expansion. These practices ensure correct handling of variables in shell scripting, preventing errors and unintended behavior. **\ ** **Search Path** 1. **Command Identification**: - The shell identifies commands by the first token/word after processing I/O redirection. - Built-in commands (e.g., echo, cd) are executed directly by the shell without searching in PATH. 2. **Searching in PATH**: - If a command name (without slashes) isn\'t a built-in, the shell looks for an executable file in directories listed in the PATH environment variable. - PATH is a colon-separated list of directories (/usr/local/bin:/bin:/usr/bin). - The shell searches these directories from left to right and executes the first match found. 3. **Exact Executable**: - Using the full pathname (/bin/date) bypasses PATH search and directly executes the specified file. 4. **Handling Multiple Matches**: - If multiple directories in PATH contain the same command name, the shell executes the first one it finds. 5. **Command Not Found**: - If a command isn\'t found in any directory listed in PATH, the shell returns a \"command not found\" error. 6. **Security Concerns**: - **Current Directory**: Avoid including the current directory (.) or adjacent colons (::) in PATH due to security risks. - Always prefix commands in the current directory with ./ to execute them explicitly. 7. **Using which and whereis**: - which identifies which directory in PATH contains a command. - whereis locates commands and their man pages in standard directories, ignoring PATH. 8. **Modifying PATH**: - Use standard shell techniques to modify PATH (export PATH=\$PATH:/new/directory). - Ensure each directory in PATH is separated correctly by colons. 9. **Shell Scripts**: - Set PATH explicitly at the start of shell scripts to ensure commands are found and executed correctly. - Failure to set PATH in scripts can lead to commands not being found, depending on the invoking environment\'s PATH. 10. **Best Practices**: - Understand how PATH works and customize it appropriately for your needs. - Avoid security risks by not including unsafe entries in PATH. Understanding these principles is crucial for effectively navigating and managing command execution in Unix-like operating systems. **Shell scripts** Shell scripting allows users to automate tasks by creating scripts containing lists of commands, executed by a shell program like bash. Scripts can be run interactively or from text files, providing flexibility and automation in system administration. **Key Points:** 1. **Interactive vs. Scripted Use:** Shells serve as interactive command interpreters for human interaction or as programming languages for executing script files stored in text format. 2. **Creating and Running Scripts:** - Scripts are lists of commands stored in text files. - Execute scripts by invoking the shell with the script file as an argument (bash script.sh or sh script.sh). - Make scripts executable (chmod +x script.sh) and run directly (./script.sh) after setting the appropriate shebang (\#!/bin/bash). 3. **Script Execution Context:** - Scripts run in their own shell process, independent of the interactive shell. - Changes to environment variables or settings in a script do not affect the interactive shell. 4. **Best Practices:** - Standard script header includes shebang (\#!/bin/bash -u), sets PATH, and specifies umask. - Use comments effectively to explain script functionality. - Store scripts in personal \~/bin directories added to \$PATH for easy execution. 5. **Handling Arguments and Variables:** - Access command-line arguments using positional parameters (\$1, \$2, etc.). - Shift parameters with shift to process multiple arguments sequentially. - Use \"\$@\" to handle multiple arguments safely. 6. **Advanced Techniques:** - Redirection (\>, \>\>) and piping (\|) allow manipulation of input and output streams. - Use for and while loops to iterate through lists of items or perform repetitive tasks. 7. **Script Security and Maintenance:** - Ensure scripts are secure by validating inputs and managing permissions (chmod). - Maintain scripts by adhering to consistent coding standards and documentation practices. **\ ** **Command Subs Arithmetic Exit** 1. **Shell Command Substitution:** - Allows substituting command output into variables or within strings using \$(command) syntax. - Example: echo \"Your userid is \$(whoami)\" - Advantages include readability, reuse of command output, and performance efficiency compared to running commands multiple times. 2. **Shell Arithmetic:** - Integer arithmetic in shell scripts is done using \$(( expression )). - Supports basic operations like addition, subtraction, multiplication (\*), division (/), and modulus (%). - Example: echo \$(( 2 + 2 \* 9 )) evaluates to 20. 3. **Decimal Point Arithmetic:** - Shell supports only integer arithmetic. For decimal calculations, use bc with quoted expressions. - Example: echo \'22/7\' \| bc -l calculates and outputs 3.14285714285714285714. 4. **Command Exit Status:** - Commands in Unix/Linux return an exit status (or return code) upon completion. - Exit status ranges from 0 (success) to 255 (various failure conditions). - Access the exit status of the last command with \$?. - Example: \$ fgrep root /etc/passwd; echo \"Exit status: \$?\" would output Exit status: 1 if no results are found. 5. **Setting Exit Status in Scripts:** - By default, a script inherits the exit status of its last executed command. - Explicitly set the script\'s exit status using exit \ within the script. - Example: exit 99 sets the script\'s exit status to 99. These concepts are fundamental for shell scripting, enabling automation, error handling, and mathematical computations within scripts effectively.

Use Quizgecko on...
Browser
Browser