💻

Understanding Parameter Passing in Shell Scripts

Aug 27, 2024

Passing Parameters in Shell Scripts

Introduction

  • Learning how to pass parameters while running shell scripts.
  • Using VS Code to create a new file.

Creating a Script

  • Open VS Code or use terminal to create a file named arguments.sh.
  • Start script with shebang: #!/bin/bash

Running the Script with Parameters

  • Example of running a script with parameters (e.g., name, number, country).
    • Command substitution example:
      • Passing parameters like my name, my number, country (e.g., India).

Accessing Parameters

  • Access parameters using the syntax:
    • $1 for the first parameter
    • $2 for the second parameter
    • $3 for the third parameter
    • Up to $9 for the ninth parameter
    • $0 returns the name of the script.

Running the Script

  1. Save the file.
  2. Change permissions: chmod +x arguments.sh
  3. Clear the screen and run the script: ./arguments.sh
  4. Pass parameters (e.g., name, country, number, tutorial).

Output Example

  • First line shows the script name, followed by parameters passed.
  • If a parameter is not used, it will show as empty.

Important Notes

  • If one parameter is passed, the others will be ignored.
  • To pass full names as a single parameter, use quotes: "Ayush Kumar"

Listing All Parameters

  • To print all arguments, use: echo "$@"

Counting Parameters

  • To count the number of parameters passed, use: echo "$#"

Storing Parameters in Variables

  • Example of storing parameter in a variable: name="$1"

Conclusion

  • Summary of how to work with parameters in shell scripts.
  • Encouragement to practice these skills.

Thank you for watching!