In shell scripting, variables enhance flexibility and reduce errors by enabling dynamic value assignment throughout your scripts. Instead of hardcoding values such as a mission name, using a variable (typically named “mission_name”) allows you to update the value in one place, ensuring consistency across all commands.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Why Use Variables?
Hardcoding values like “lunar-mission” in every command can lead to issues:- Inconsistencies: A single typo can disrupt the entire script.
- Maintenance Challenges: Adding or modifying steps requires updating every instance manually.
- Poor Reusability: Reusing the script for another mission (e.g., Mars mission) involves replacing each occurrence, increasing error risks.
Basic Variable Usage
When referencing a variable in a script, always prefix its name with a dollar sign ($). However, omit the dollar sign when assigning a value. Below is an improved example of how to set and use a variable in a shell script:
Variable names should use only lowercase letters and underscores (e.g.,
mission_name). Avoid using hyphens or other characters, as variable names must consist solely of alphanumeric characters or underscores.Capturing Command Output in Variables
Variables in shell scripts can also store the output of commands. For instance, if the commandrocket-status outputs a value such as “launching”, “success”, or “failed”, you can capture that output and then display it. The following example demonstrates how to do this:
rocket-status is stored in the variable rocket_status using the command substitution syntax $(...) and then printed using the echo command.