Shell Script · Script Arguments

Shell Scripting · Lesson 16

Script Arguments

Pass arguments to shell script from command line. Use $1 $2 and special variables. Create flexible admin scripts. Production style usage.

What Are Script Arguments?

Script arguments are values passed to a shell script when it is executed. They allow scripts to behave dynamically based on user input.

Why Use Script Arguments?

Dynamic Execution

Run same script with different inputs.

Automation

Useful in automation and batch scripts.

Parameter Handling

Easily manage multiple input values.

Positional Parameters

  • $0 – Script name
  • $1 – First argument
  • $2 – Second argument
  • $# – Number of arguments
  • $@ – All arguments individually
  • $* – All arguments as a single string

Script Argument Examples

1. Basic Script Arguments

Pass arguments while running the script from terminal.

terminal — bash
script-args
#!/bin/bash
echo "First argument: $1"
echo "Second argument: $2"
 
# Run:
# ./script.sh hello world

2. Counting Arguments

Use $# to get total number of arguments.

terminal — bash
script-args
#!/bin/bash
echo "Total arguments: $#"

3. Access All Arguments

Use $@ or $* to access all arguments.

terminal — bash
script-args
#!/bin/bash
echo "All arguments: $@"
echo "All arguments as single string: $*"

4. Loop Through Arguments

Iterate through all arguments using a loop.

terminal — bash
script-args
#!/bin/bash
 
for arg in "$@"
do
echo "Argument: $arg"
done

5. Using shift Command

Shift removes the first argument and shifts others.

terminal — bash
script-args
#!/bin/bash
 
while [ $# -gt 0 ]
do
echo "Argument: $1"
shift
done

Best Practices

Recommended Practices

  • Always validate number of arguments.
  • Use meaningful variable names.
  • Quote arguments to avoid word splitting.
  • Use shift for processing arguments dynamically.

Practice Task – Script Arguments

  • Create a script that accepts two numbers and prints their sum.
  • Create a script that prints all arguments one by one.
  • Validate minimum two arguments are passed.

Next lesson: Exit Status & Error Handling