Skip to content

Q&A · Answered

How to create shell script with arguments

asked 9 months, 1 week ago 799 views 1 answer
36

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

1 Answer

One accepted
14

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
#!/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

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.