How To Write Bash Scripts In Linux - Complete Guide (Part 16 - Arguments)
Introduction to Bash Script Arguments
Understanding Arguments in Bash Scripts
- The episode focuses on adding arguments to bash scripts, allowing them to perform different actions based on user input.
- A simple script is introduced that uses the
echocommand to display a message incorporating an argument passed during execution.
- The variable
$1represents the first argument provided when running the script, demonstrating how arguments replace variables without explicit declaration.
Multiple Arguments and Their Usage
- The script can handle multiple arguments, with
$1,$2,$3, etc., representing each subsequent argument.
- An example is given where four personal interests are passed as arguments, showcasing how they are displayed in the output.
Practical Applications of Arguments
Real-world Examples of Argument Use
- Commands like
ls -l /etcillustrate how arguments modify command behavior; here,/etcserves as an argument for listing directory contents.
- A new example script is created using
ls -lh $1, emphasizing that while it may not be practical, it effectively demonstrates argument functionality.
Enhancing Script Utility
- The importance of arguments is highlighted through potential use cases such as backup scripts that require specific paths as input for operation.
Advanced Scripting Techniques
Counting Directory Objects with Arguments
- A more complex script counts objects in a specified directory by piping
ls -lh $1intowc -l.
- This approach provides a count of items within the directory referenced by the user's input, enhancing utility over previous examples.
Error Handling and User Input Validation
- The discussion shifts to error handling; if no argument is provided, invalid output occurs. This highlights the need for user input validation.
Implementing Input Checks
Ensuring Correct Argument Count
- An if statement checks whether exactly one argument has been supplied using
$#, which counts provided arguments.
- If conditions aren't met (e.g., no or multiple arguments), informative messages guide users on correct usage and exit codes are managed accordingly.
Conclusion and Next Steps
Preparing for Future Lessons
- The next lesson will focus on creating a backup script requiring user-defined paths as arguments, reinforcing learned concepts about scripting with inputs.