How to use command-line arguments?

082

Using command-line arguments allows you to pass information to scripts or programs when you run them from the command line. Here’s how to use command-line arguments in both Bash scripts and Python programs:

In Bash Scripts

  1. Accessing Arguments: You can access command-line arguments using special variables:

    • $1, $2, $3, etc. for the first, second, third arguments, and so on.
    • $@ for all arguments.
    • $# for the number of arguments.
  2. Example Script:

    #!/bin/bash
    echo "First argument: $1"
    echo "Second argument: $2"
    echo "Total number of arguments: $#"
  3. Running the Script:

    ./script.sh arg1 arg2

In Python Programs

  1. Using sys.argv: You can access command-line arguments using the sys module.

    • sys.argv is a list where the first element is the script name and subsequent elements are the arguments.
  2. Example Script:

    import sys
    
    if len(sys.argv) > 1:
        print("First argument:", sys.argv[1])
        print("Second argument:", sys.argv[2])
        print("Total number of arguments:", len(sys.argv) - 1)
    else:
        print("No arguments provided.")
  3. Running the Script:

    python script.py arg1 arg2

Summary

  • In Bash, use $1, $2, etc., to access arguments.
  • In Python, use sys.argv to access command-line arguments.
  • Always check the number of arguments to avoid index errors.

If you have any specific use cases or need further examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!