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
-
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.
-
Example Script:
#!/bin/bash echo "First argument: $1" echo "Second argument: $2" echo "Total number of arguments: $#" -
Running the Script:
./script.sh arg1 arg2
In Python Programs
-
Using
sys.argv: You can access command-line arguments using thesysmodule.sys.argvis a list where the first element is the script name and subsequent elements are the arguments.
-
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.") -
Running the Script:
python script.py arg1 arg2
Summary
- In Bash, use
$1,$2, etc., to access arguments. - In Python, use
sys.argvto 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!
