DEV Community

Andrew (he/him)
Andrew (he/him)

Posted on

5

Easily Inspect Arguments Passed to a bash Script

Have you ever had problems with bash scripts? Not understanding why they're not working? Sometimes, you just need to echo the arguments to make sure they're being interpreted correctly:

#!/usr/bin/env bash
#-------------------------------------------------------------------------------
#
# print_args - easily inspect arguments passed to a bash script
#
# sources:
# https://unix.stackexchange.com/a/332126/183920
#
#-------------------------------------------------------------------------------
function print_args {
echo "arguments:"
local ii=1
for arg; do
printf " \$%u: '%s'\n" "$ii" "$arg"
((ii++))
done
}
# usage:
#
# $ print_args 3 "3.a" "hello world"
# arguments:
# $1: '3'
# $2: '3.a'
# $3: 'hello world'
function example {
echo "printing arguments passed to 'example'..."
printargs "$@"
echo "...done."
printf "\$2 = %s\n" "$2"
}
# example:
#
# $ example "a b" 5.5 ho-ho
# printing arguments passed to 'example'...
# arguments:
# $1: 'a b'
# $2: '5.5'
# $3: 'ho-ho'
# ...done.
# $2 = 5.5
view raw printargs.sh hosted with ❤ by GitHub

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay