Geavanceerd
Zoeken inSamenvattingen
Zo zoek je
  • Woorden vinden lestitels, tekst en code. Filter op soort (gidsen, cursussen, programma's, boeken) of blijf in dit boek.
  • book:rhcsa en ch:8 maken de zoektocht kleiner; #code vindt een woord alleen in commando's van de lessen.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Hoofdstuk 32Naam in het boek: Positional Parameters

Positional parameters and options

Real commands take options and arguments: ls -l /etc. Scripts can do the same. The words after the script name arrive in positional parameters $1, $2 … This chapter shows how to read them, count them, walk through them with shift, use them in functions, and add options like -f file and -i to the report script.

  • 9 Lessen
  • 3 Commando's
  • 1 Labs

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

Vaardigheden in dit hoofdstuk

  • Scripts argumenten en opties geven

32.1

Read the command line

$0 is the name of the script; $1 to $9 are the first nine arguments. From 10 on, use braces: ${10}.

posit-param
#!/bin/bash
 
# posit-param: script to view command line parameters
 
echo "
\$0 = $0
\$1 = $1
\$2 = $2
\$3 = $3
"
posit-param a b c d
 
$0 = /home/me/bin/posit-param
$1 = a
$2 = b
$3 = c

32.2

Count the arguments with $#

$# holds the number of arguments.

set -- a b c d
echo "$#"
4
posit-param *
  • set -- words sets the positional parameters in the current shell: good for testing.
  • With a wildcard, many file names can arrive. $# tells how many.

32.3

Walk through the arguments with shift

shift moves every argument one place down: $2 becomes $1, $3 becomes $2, and $# gets 1 smaller. With a loop you can handle any number of arguments.

posit-param2
#!/bin/bash
 
# posit-param2: script to display all arguments
 
count=1
 
while [[ $# -gt 0 ]]; do
    echo "Argument $count = $1"
    count=$((count + 1))
    shift
done
posit-param2 a b c d
Argument 1 = a
Argument 2 = b
Argument 3 = c
Argument 4 = d

32.4

Write a simple tool

A small script that shows information about a file given as an argument. ${0##*/} gives the script name without the path.

file-info
#!/bin/bash
 
# file-info: simple file information program
 
PROGNAME="${0##*/}"
 
if [[ -e "$1" ]]; then
    echo -e "\nFile Type:"
    file "$1"
    echo -e "\nFile Status:"
    stat "$1"
else
    echo "$PROGNAME: usage: $PROGNAME file" >&2
    exit 1
fi

32.5

Use parameters in functions

Inside a function, $1, $2 … and $# are the function's arguments, not the script's. $0 stays the script name; FUNCNAME holds the function name.

a function with an argument
file_info () {
    # file_info: function to display file information
    if [[ -e "$1" ]]; then
        echo -e "\nFile Type:"
        file "$1"
        echo -e "\nFile Status:"
        stat "$1"
    else
        echo "$FUNCNAME: usage: $FUNCNAME file" >&2
        return 1
    fi
}

32.6

Handle all parameters with $@ and $*

$* and $@ stand for all arguments. Only "$@" (with quotes) keeps each argument as it was, also with spaces.

FormResult for the arguments word and words with spaces
$*4 words: word, words, with, spaces
"$*"1 word: "word words with spaces"
$@4 words (like $*)
"$@"2 words: "word", "words with spaces"
posit-params3
#!/bin/bash
 
print_params () {
    echo "\$1 = $1"
    echo "\$2 = $2"
    echo "\$3 = $3"
    echo "\$4 = $4"
}
 
pass_params () {
    echo -e "\n" '"$@" :'; print_params "$@"
    echo -e "\n" '$* :';   print_params $*
}
 
pass_params "word" "words with spaces"

Onthoud

Use "$@" to pass all arguments to another command. It is right in almost every case.

32.7

Add options to the report script

Read options in a while loop with case and shift: -f file writes the report to a file, -i asks for the file name, -h shows help.

option handling in sys_info_page
usage () {
    echo "$PROGNAME: usage: $PROGNAME [-f file | -i]"
    return
}
 
# process command line options
interactive=
filename=
 
while [[ -n "$1" ]]; do
    case "$1" in
        -f | --file)        shift
                            filename="$1"
                            ;;
        -i | --interactive) interactive=1
                            ;;
        -h | --help)        usage
                            exit
                            ;;
        *)                  usage >&2
                            exit 1
                            ;;
    esac
    shift
done
write to a file or to the screen
if [[ -n "$filename" ]]; then
    if touch "$filename" && [[ -f "$filename" ]]; then
        write_html_page > "$filename"
    else
        echo "$PROGNAME: Cannot write file '$filename'" >&2
        exit 1
    fi
else
    write_html_page
fi
  • The page itself moves into a function write_html_page; the script sends it to a file or to stdout.
  • In -i mode the script asks for a file name with read and asks before it overwrites an existing file.

Commando's in deze les

32.8

Use getopts for short options

The builtin getopts parses short options (also joined, like -vf file) for you. A : after a letter means the option needs a value.

getopts example
verbose=0
file=""
 
while getopts ":vf:h" opt; do
    case "$opt" in
        v) verbose=1 ;;
        f) file="$OPTARG" ;;
        h) echo "usage: ${0##*/} [-v] [-f file]"; exit 0 ;;
        :) echo "option -$OPTARG needs a value" >&2; exit 1 ;;
        ?) echo "unknown option -$OPTARG" >&2; exit 1 ;;
    esac
done
shift $((OPTIND - 1))
echo "verbose=$verbose file=$file rest=$*"
  • OPTARG holds the value of the option; OPTIND the index of the next argument. shift $((OPTIND - 1)) leaves only the normal arguments.
  • getopts does not understand long options (--file). For those, use the while/case loop above.

32.9

Summary of the chapter

$1…${10}, $#, shift, "$@", and a while + case loop (or getopts) give scripts real options.

1How do you get the 11th argument?

${11} (braces are needed from 10 on).

2Why use "$@" instead of $*?

"$@" keeps each argument as one word, also when it contains spaces.

3What does shift do?

It drops $1 and moves all other arguments one place down; $# becomes one smaller.

Oefenen

Alle commando's in dit hoofdstuk