36
How do I write a bash script that accepts command line arguments?
Loading...
Q&A · Answered
How do I write a bash script that accepts command line arguments?
Accepted answer
#!/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
doneSay what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.