Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

documenting shell scripts' parameters

Tags:

linux

shell

unix

People also ask

How do you pass a parameter to a shell script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded.

What is $1 and $2 in shell script?

$0 is the name of the script itself (script.sh) $1 is the first argument (filename1) $2 is the second argument (dir1) $9 is the ninth argument.

What is $@ and $* in shell script?

"$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...). So basically, $# is a number of arguments given when your script was executed. $* is a string containing all arguments. For example, $1 is the first argument and so on.


Traditionally you document your arguments in the usage() function:

#!/bin/bash

programname=$0

function usage {
    echo "usage: $programname [-abch] [-f infile] [-o outfile]"
    echo "  -a      turn on feature a"
    echo "  -b      turn on feature b"
    echo "  -c      turn on feature c"
    echo "  -h      display help"
    echo "  -f infile   specify input file infile"
    echo "  -o outfile  specify output file outfile"
    exit 1
}

usage

I would recomment using a heredoc:

usage () {
    cat <<HELP_USAGE

    $0  [-a] -f <file>

   -a  All the instances.
   -f  File to write all the log lines
HELP_USAGE
}

instead of:

echo "$0  [-a] -f <file>"
echo
echo "-a  All the instances."
echo "-f  File to write all the log lines."

I think it is way cleaner than all these echo lines.


I usually wrap my usage in function so I can call it from a -h param etc.

#!/bin/bash
usage() {
    cat <<EOM
    Usage:
    $(basename $0) Explain options here

EOM
    exit 0
}

[ -z $1 ] && { usage; }

The Vim bash IDE that does this:

#!/bin/bash
#===============================================================================
#
#          FILE:  test.sh
#
#         USAGE:  ./test.sh
#
#   DESCRIPTION:
#
#       OPTIONS:  ---
#  REQUIREMENTS:  ---
#          BUGS:  ---
#         NOTES:  ---
#        AUTHOR:  Joe Brockmeier, [email protected]
#       COMPANY:  Dissociated Press
#       VERSION:  1.0
#       CREATED:  05/25/2007 10:31:01 PM MDT
#      REVISION:  ---
#===============================================================================