Linux_ Summary of Chapter 14 of Linux command line and shell script programming

Time:2021-10-16

Time: Tuesday, September 19, 2017
Note: some of the contents of this article are taken from the book “complete collection of Linux command line and shell script programming”, and the copyright belongs to the original author. Summary of Chapter 14 of Linux command line and shell script programming (Third Edition)

Chapter 14: processing user input

Contents of this chapter

Transfer parameters
Tracking parameters
Move variable
Processing options
Standardize options
Get user input

14.1 command line parameters

14.1.1 reading parameters

The bash shell assigns special variables called positional parameters to all parameters entered on the command line.

Position parameter variables are standard numbers

$0 is the program name
$1 is the first parameter
$2 is the second parameter
And so on to know the ninth parameter $9

Write test1.sh script

#!/bin/bash

factorial=1
for (( number=1;number<=$1;number++ ))
do
    factorial=$[ $factorial * $number ]
done
echo The factorial of $1 is $factorial

Execute command

./test1.sh 5

Write test2.sh script

#!/bin/bash

total=$[ $1 * $2 ]
echo The first paramter is $1.
echo The second paramter is $2.
echo Thetotal paramter is $total.

Execute command

./test2.sh 2 5

Write test3.sh script

#!/bin/bash
echo Hello $1,glad to meet you.

Execute command

./test3.sh 'Rich Blum'

If the script requires more than 9 command-line parameters, use ${10} to obtain them

Write test4.sh script

#!/bin/bash
total=$[  *  ]
echo The tenth parameter is 
echo The eleventh parameter is 
echo The total is $total

Execute command

./test4.sh 1 2 3 4 5 6 7 8 9 10 11 12

14.1.2 read script name

Use the $0 parameter to get the name of the script that the shell starts on the command line

Write test5.sh script

#!/bin/bash
echo The zero parameter is set to:$0

Execute command

bash test5.sh 

Use the basename command to get a script name that does not contain a path

Write test5b.sh

#!/bin/bash
name=$(basename $0)
echo
echo The script name is:$name

Use this method to write scripts that perform different functions based on the script name

Write test6.sh script

#!/bin/bash
name=$(basename $0)

if [ $name = "addem" ]
then
    total=$[ $1 + $2 ]
elif [ $name = "multem" ]
then
    total=$[ $1 * $2 ]
fi

echo
echo The calculated value is $total

Execute command

cp test6.sh addem
cp test6.sh multem
./addem 2 5
./multem 2 5

14.1.3 test parameters

Before using parameters, the script needs to check whether there is data in it

Write test7.sh script

#!/bin/bash
if [ -n "$1" ]
then
    echo Hello $1,glad to meet you.
else
    echo "Sorry,you did not identify yourself."
fi

Execute command

./test7.sh Rich
./test7.sh

14.2 special parameter variables

14.2.1 parameter statistics

The special variable $# contains the number of command line parameters carried by the script runtime

Write test8.sh script

#!/bin/bash
echo There were $# parameters supplied.

Execute command

./test8.sh
./test8.sh 1 2 3 4 5
./test8.sh "Rich Blum"

Write the test9.sh script

#!/bin/bash
if [ $# -ne 2 ]
then
    echo
    echo Usage:test9.sh a b
    echo
else
    total=$[ $1 + $2 ]
    echo
    echo The total is $total
    echo
fi

Execute command

./test9.sh
./test9.sh 10
./test9.sh 10 15

Gets the last command line parameter variable

Write test10.sh script

#!/bin/bash
params=$#
echo
echo The total parameter is $params
echo The last parameter is ${!#}
echo

Execute command

./test10.sh
./test10.sh 1 2 3
./test10.sh 1 2 3 4

14.2.2 capture all data

Use $* and [email protected] variables to access all parameters
When traversing these two variables with the for command
The $* variable treats all parameters as a single parameter
The [email protected] variable handles each parameter separately

Write test11.sh script

#!/bin/bash
echo
echo "Using the $* method:$*"
echo "Using the [email protected] method:[email protected]"
echo

Execute command

./test11.sh rich barbara katie jseeica

Write test12.sh script

#!/bin/bash
echo
count=1
for param in "$*"
do
    echo "$* parameter #Scount = $param"
    count=$[ $count + 1 ]
done
echo
count=1
for param in "[email protected]"
do
    echo "[email protected] parameter #Scount = $param"
    count=$[ $count + 1 ]
done

Execute command

./test12.sh rich barbara katie jseeica

14.3 moving variables

The shift command moves command-line parameters based on their relative position

Knock on the door: be careful when using the shift command. If a parameter is removed, its value is discarded and cannot be recovered

Write test13.sh script

#!/bin/bash
echo
count=1
while [ -n "$1" ]
do
    echo "Parameter #$count = $1"
    count=$[ $count+1 ]
    shift
done

Execute command

./test13.sh rich barbara katie jessica

Write test14.sh script

#!/bin/bash
echo
echo "The original parameters: $*"
shift 2
echo "Here's the new first parameter: $1"

Execute command

./test14.sh 1 2 3 4 5

14.4 processing options

14.4.1 search options

1. Handling simple options

When extracting each individual parameter, use the case statement to judge whether a parameter is an option

Write test15.sh script

#!/bin/bash
echo
while [ -n "$1" ]
do
    case "$1" in
        -a) echo "Found the -a option" ;;
        -b) echo "Found the -b option" ;;
        -c) echo "Found the -c option" ;;
        *) echo "Found the an option" ;;
    esac
    shift
done

Execute command

./test15.sh -a -b -c -d

2. Separation parameters and options

Linux distinguishes between options and parameters by double broken lines (- -)

Write test16.sh script

#!/bin/bash
echo
while [ -n "$1" ]
do
    case "$1" in
        -a) echo "Found the -a option" ;;
        -b) echo "Found the -b option" ;;
        -c) echo "Found the -c option" ;;
        --) shift
            break ;;
        *) echo "$1 is not an option" ;;
    esac
    shift
done
#
count=1
for param in [email protected]
do
    echo "Parameter #count:$param"
    count=$[ $count+1 ]
done

Execute command

./test16.sh -a -b -c test1 test2 test3
./test16.sh -a -b -c -- test1 test2 test3

3. Handle options with values

Some options carry an additional parameter value, which the script must be able to detect and handle correctly

Write test17.sh script

#!/bin/bash
echo
while [ -n "$1" ]
do
    case "$1" in
        -a) echo "Found the -a option" ;;
        -b) param="$2"
            echo "Found the -b option,with parameter value $param"
            shift ;;
        -c) echo "Found the -c option" ;;
        --)
            shift
            break ;;
        *) echo "$1 is not an option";;
    esac
    shift
done
#
count=1
for param in [email protected]
do
    echo "Parameter #$count:$param"
    count=$[ $count+1 ]
done

Execute command

./test17.sh -a -b test1 -d
./test17.sh -b test1 -a -d

14.4.2 using the getopt command

The getopt command is a very convenient tool for handling command options and parameters. It recognizes command-line parameters, making it easier to parse them in scripts.

1. Format of command

Command format: getopt optstring parameters
Command description: getopt command can accept a series of command line options and parameters in any form

Knock on the door: there is a more advanced version of the getopt command called getopts (note that this is in the plural). The getopts command will be reduced to later in this chapter. Because the spelling of the two commands is almost the same, it is easy to be confused. Be careful.

Command demonstration: getopt AB: CD – A – B test1 – CD test2 test3
Presentation results: – A – B test1 – C – D – test2 test3
Demo Description: optstring defines four valid option letters: A, B, C and D. The colon (:) is placed after the letter B because the B option requires a parameter value. When the getopt command runs, it checks the supplied parameter list (- A – B test1 – C – D – test2 test3) and parses it based on the supplied optstring. Note that it automatically divides the – CD option into two separate options and inserts a double broken line to split the additional parameters in the row.

Getopt description

If you specify an option that is not in optstring, the getopt command generates an error message
If you want to ignore this error message, you can add the - Q option after the command
The getopt command option must appear before optstring
The getopt command is not good at handling parameter values with spaces and quotes

2. Use getopt in the script

Write test18.sh script

#!/bin/bash
#
set -- $(getopt -q ab:cd "[email protected]")
#
echo
while [ -n "$1" ]
do
    case "$1" in
        -a) echo "Found the -a option" ;;
        -b) param="$2"
            echo "Found the -b option, with parameter value $param"
            shift ;;
        -c) echo "Found the -c option" ;;
        -d) echo "Found the -d option" ;;
        --) shift
            break ;;
        *)  echo "$1 is not an option" ;;
    esac
    shift
done
#
count=1
for param in "[email protected]"
do
    echo "Parameter #$count:$param"
    count=$[ $count+1 ]
done

Execute command

./test18.sh -ac
./test18.sh -a -b test1 -cd test2 test3 test4

14.4.3 using more advanced getopts

The getopts command (note the plural) is built into the bash shell.

Command format: getopts optstring variable
Command description: optstring is the same as that in getopt command

Use the optarg environment variable to get the parameter value of the option

Write test19.sh script

#!/bin/bash
echo
while getopts :ab:c opt
do
    case "$opt" in
        a) echo "Found the -a option" ;;
        b) echo "Found the -b option, with value $OPTARG" ;;
        c) echo "Found the -c option" ;;
        *) echo "Unknown option: $opt" ;;
    esac
done

Execute command

./test19.sh -ab test1 -c
./test19.sh -b "test1 test2" -a
./test19.sh -abtest1
./test19.sh -acde

Use the shift command and the optind value to move parameters

Write the test20.sh script

#!/bin/bash
echo
while getopts :ab:cd opt
do
    case "$opt" in
    a) echo "Found the -a option" ;;
    b) echo "Found the -b option, with value $OPTARG" ;;
    c) echo "Found the -c option" ;;
    d) echo "Found the -d option" ;;
    *) echo "Unknown option: $opt" ;;
    esac
done
#
shift $[ $OPTIND - 1 ]
#
echo
count=1
for param in "[email protected]"
do
    echo "Parameter $count: $param"
    count=$[ $count+1 ]
done

Execute command

./test20.sh -a -b test1 -d test2 test3 test4

14.5 standardizing options

When you create a shell script, you can decide which letters to use and their usage

But some alphabetic options already have some standard meaning in the Linux world

Common Linux command options

Options: description
-a: Show all objects
-c: Generate a count
-d: Specify a directory
-e: Extend an object
-f: Specifies the file to read in the data
-h: Displays help for the command
-i: Ignore text case
-l: Produces a long format version of the output
-n: Use non interactive mode (batch)
-o: Redirects all output to the specified output file
-q: Run in quiet mode
-r: Recursively process directories and files
-s: Run in quiet mode
-v: Generate detailed output
-x: Exclude an object
-y: Answer yes to all questions

14.6 obtaining user input

14.6.1 basic reading

The read command accepts input from standard input (keyboard) or another file descriptor.

Write test21.sh script

#!/bin/bash
echo -n "Enter your name:"
read name
echo "Hello $name,welcome to my program."

Write test22.sh script

#!/bin/bash
read -p "Please enter your age:" age
days=$[ $age * 365]
echo "That makes you over $days days old!"

Write test23.sh script

#!/bin/bash
read -p "Enter your name:" first last
echo "Checking data for $last, $first..."

The read command puts any data it receives into the special environment variable reply

Write the test24.sh script

#!/bin/bash
read -p "Enter your name:"
echo
echo Hello $REPLY, welcome to my program.

14.6.2 timeout

When using the read command, you can use the – t option to specify the number of seconds the read command waits for input. When the counter expires, the read command returns a non-zero exit status code

Write test25.sh

#!/bin/bash
if read -t 5 -p "Please enter your name:" name
then
    echo "Hello $name,welcome to my script"
else
    echo
    echo "Sorry,too slow!"
fi

Use the – N option of the read command to count the number of characters entered. When the input character reaches the preset number of characters, it will automatically exit and assign the input data to the variable

Write the test26.sh script

#!/bin/bash
read -n1 -p "Do you want to continue [Y/N]?" answer
case $answer in

Y | y)  echo
        echo "fine,continue on..." ;;
N | n)  echo
        echo "OK,goodbay"
        exit;;
esac
echo "The is the end of the script"

14.6.3 hidden reading

Use the – s option to hide the data output from the read command to avoid appearing directly on the display

Write the test27.sh command

#!/bin/bash
read -s -p "Enter your password:" pass
echo
echo "Is your password really $pass?"

14.6.4 read from file

Use read to read the data saved in the file on the Linux system. Each time the read command is called, it reads a line of data from the file. When there is no content in the file, the read command exits and returns a non-zero exit status code

Write test text

One
Two
Three

Write the test28.sh script

#!/bin/bash
count=1
cat test | while read line
do
    echo "line $count: $line"
    count=$[ $count+1 ]
done
echo "Finished processing the file"

14.7 summary

This chapter describes three different ways to obtain data from script user processing. Command line parameters allow users to enter data directly from the command line when running a script. The script retrieves command-line parameters through positional parameters and assigns them to variables