How to create shell script with arguments

Answered
Jan 05, 2026 356 views 1 answers
36

How do I write a bash script that accepts command line arguments?

O
Asked by omar_linux
Platinum 593 rep

1 Answer

14
#!/bin/bash
# myscript.sh

# Access arguments
echo "Script name: $0"
echo "First arg: $1"
echo "Second arg: $2"
echo "All args: $@"
echo "Arg count: $#"

# Check if arg provided
if [ -z "$1" ]; then
    echo "Usage: $0 "
    exit 1
fi

# Named arguments with getopts
while getopts "n:v" opt; do
    case $opt in
        n) NAME="$OPTARG" ;;
        v) VERBOSE=true ;;
    esac
done
L
Answered by linux_expert 1 week, 2 days ago
Bronze 311 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer