Interacting with a Linux system often requires providing input and parameters to commands or scripts. This can be done using command-line arguments or user input. In this article, we explore how to handle command-line arguments and gather user input in Linux shell scripts.
Command Line Arguments
Command-line arguments are values passed to a script when it is executed. These arguments can be accessed inside the script and used to control its behavior dynamically.
Syntax:
#!/bin/bash
# Accessing command line arguments
echo "The first argument is: $1"
echo "The second argument is: $2"
When you run the script with , it will output:
The first argument is: arg1
The second argument is: arg2
Using $# and $@
- $#: Represents the total number of command-line arguments
- $@: Represents all command-line arguments as a list
#!/bin/bash
echo "Total number of arguments: $#"
echo "All arguments: $@"
Example: Summing Numbers
#!/bin/bash
sum=$(( $1 + $2 ))
echo "The sum of $1 and $2 is: $sum"
Run the script as:
./script.sh 3 5Output:
The sum of 3 and 5 is: 8User Input
The command allows you to prompt the user for input during script execution.
#!/bin/bash
echo "Enter your name:"
read name
echo "Hello, $name!"
Example: Calculator Using User Input
#!/bin/bash
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2
sum=$(( num1 + num2 ))
echo "The sum is: $sum"
Run the script to input two numbers and get their sum.
Handling Password Input Securely
To handle sensitive information like passwords, you can use the option with to hide the input:
#!/bin/bash
echo "Enter your password:"
read -s password
echo "Password entered."
# Process the password securely
The -s option ensures that the password is not displayed on the screen while typing.