Scripting Syntax

Shell variables are not typed, meaning that you do not specify whether a variable is a string or a number (or whatever).

Variables are declared and assigned in one statement using the equal sign: for example,

counter = 0
custname = "Harold Davis"

If a string has no embedded spaces, you do not need to use quotation marks.

A $ is used to assign the contents of one variable to another: for example,

counter = $myvar

Using command-line parameters

  • You can pass a shell script command-line parameters and retrieve them from inside the script. The first command-line parameter is referenced as $1, the second as $2, and so on.

    The following script illustrates how this works:

    # Display that command line _ 
      parameter 
    if [ $# -eq 0 ] 
    then 
      echo "Please provide a _     command line name!" 
    else 
      echo "Hello"  $1
    fi
    

    If you save this script as invoke and run it with no command-line parameters, the shell script asks, "Please provide a command line name!" Otherwise, the name you entered on the command line is echoed back (Figure 12.12).

    By the way, fi is not a typo—it is if spelled backward, and it represents the end of an if statement. In a similar fashion, case statements are ended with esac.

    In the script, $# is a built-in variable containing the number of command-line variables (see Table 12.1). The entry –eq is used to compare $# with 0 (see Table 12.2). The entry $1 represents the first command-line variable.

To accept interactive user input:

1.
Open a text editor.

2.
Type the following script:

#! /bin/bash
# Interactive user input

echo "Enter your name:"
read yrname
echo "Is it time for tea, $yrname?"

3.
Save the file as yrname.

4.
At the command line, change the file to make it executable:

chmod +x yrname

5.
Run the script by typing yrname.

The script will prompt for a name and then echo it (Figure 12.13).

Tip

By placing read statements within infinite loops, you can create menus and menu-driven applications.


Tip

You are better off programming anything other than very simple tasks in a language such as Perl than as a shell script. Longer scripts are very hard to read and debug.


Figure 12.13. To accept interactive user input in a script, use the read command.


Built-in Variables
RepresentationMeaning
$#Number of command-line arguments passed to the shell
$0The name of the shell program
$*A single string made up of all the command-line arguments

Comparison Operators
OperatorMeaning
=String equality
!=String inequality
-eqArithmetic equality
-geArithmetic greater than or equal to
-leArithmetic less than or equal to
-neArithmetic not equal to
-gtArithmetic greater than
-ltArithmetic less thanf

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.237.164