Shell Programming Basics

Source: Internet
Author: User
Tags stdin syslog

Before we write, let's figure out why we need to learn the shell and learn to be purposeful.
The shell is simple, flexible, and efficient, and is especially suitable for dealing with some minor system management issues.
Shell automates management, making it easy, easy, and efficient for system administrators to work
Shell scripts are portable and can be ported flexibly in the Unix/linux system, with virtually no setup to run properly
Shell scripting makes it easy to read and modify source code without compiling
Mastering the shell can help you troubleshoot problems such as script-induced failures
Mastering the shell is a must-have for an intermediate or above system engineer
Mastering the shell is the only way for you to manage the advanced system.
Mastering the shell is a stepping stone to your higher-level job interview.
When does the shell script not be used?
resource-intensive tasks, especially when you need to consider efficiency (such as sorting, hashing, etc.)
Mathematical operations that need to handle large tasks, especially floating-point operations, precision operations, or complex arithmetic operations (typically handled using C + + or FORTRAN)
Cross-platform porting requirements (typically using C or Java)
Complex applications where structured programming must be used (need for variable type checking, function prototypes, etc.)
For mission-critical applications that affect the overall system.
Tasks that require a high level of security, such as the need for a robust system to prevent intrusion, cracking, vandalism, and so on.
A project consists of various parts of a chain of dependencies.
Requires large-scale file operations
Support for multidimensional arrays required
Requires data structure support, such as linked lists or data structures
Need to produce or manipulate graphical interface GUI
Requires direct operating system hardware
I/O or socket interface required
Interfaces that require the use of libraries or legacy old code
Private, closed-source applications (shell scripts put the code in a text file that the world can see)
If your app fits any of the above, consider a more powerful language-perhaps Perl,python,ruby, or a higher-level compiler language such as C/c++,java.

1. Introducing Shell Scripts

Simply put, the shell is a file containing several lines of shell or Linux commands. For a large number of commands that are written and used more than once, you can save them using a separate file,

For later use. Typically, shell scripts are suffixed with. Sh . When writing the shell, the first line must indicate which shell the system needs to interpret the user's shell , such as: #!/bin/sh,#!/bin/bash,#!/bin/csh,,#!/bin/tcsh and, #!/bin/ Ksh and so on. The following run.sh indicates the use of bash execution.

#!bin/bash

Ls-l

Typically,shell scripts use #!/bin/sh as the default shell program . There are two ways to execute a shell: The first is to add executable permissions to the shell script and execute it, and the second is to execute the shell script through the SH command, such as executing the run.sh script under the current directory, with the following command:

Add executable permissions directly to the shell script and execute

chmod 755 run.sh

./run.sh

Execute shell script with sh command

SH run.sh

Note: Why can "sh shell.sh" also run?

This is because/bin/sh is actually/bin/bash (link file), using SH shell.sh that tells the system, I want to run the bash directly to the function of the shell.sh the relevant command in this file meaning, so at this time your shell.sh as long as there is R Permissions can be run Oh! And we can also use SH parameters, such as-N and-X to check and trace shell.sh syntax is correct?

2. Input and output redirection

Linux uses standard input stdin and standard output stdoutto represent the input and output of each command, and also uses a standard error output stderr for output error messages. these three standard input and output systems are linked by default to the control terminal . Therefore, in standard cases, each command usually obtains input from its control terminal and prints the output to the screen of the control terminal.

However, you can redefine the input stdin and output stdout of the program to redirect them. The most basic way is to redefine them to a file, getting input/output from one file to another medium.

2.1 Input Redirection

input redirection using less than sign "<" can be implemented. The cat command to display the file is to redirect the standard input to the file implementation.

REDIRECT/etc/fstab as input to the cat command

# Cat/etc/fstab

[Plain]View PlainCopy
  1. label=//ext3 Defaults 1 1
  2. Label=/boot/boot ext3 Defaults 1 2
  3. None/dev/pts devpts gid=5,mode=620 0 0
  4. NONE/PROC proc Defaults 0 0
  5. NONE/DEV/SHM TMPFS Defaults 0 0
  6. /dev/hda3 swap swap defaults 0 0
  7. /dev/cdrom/mnt/cdrom udf,iso9660 Noauto,owner,kudzu,ro 0 0
  8. /dev/fd0/mnt/floppy Auto Noauto,owner,kudzu 0 0

2.2 Output redirection

There are two ways to output redirection, one is direct output , one is to use a greater than sign ">" , the other is output in an additional way , using two greater than sign ">>" implementations. the former overwrites the original output , and the latter is added to the end of the file. The differences are illustrated by examples below.

The LS command redirects to/root/dir.txt and displays

LS >dir.txt

Cat < Dir.txt

Anaconda-ks.cfg

Install.log

Install.log.syslog

The ls-l command redirects to/root/dir.txt in an additional way and displays

Ls-l >>dir.txt

Cat < Dir.txt

Anaconda-ks.cfg

Install.log

Install.log.syslog

Total Dosage 24

-rw-r--r--1 root root 1245 July 21:07 anaconda-ks.cfg

-rw-r--r--1 root root 14522 July 21:01 intall.log

-rw-r--r--1 root root 2906 July 21:00 install.log.syslog

3. Pipeline

Piping and input-output redirection are very similar. The purpose of a pipeline is to establish a channel between the standard output of one command and the standard input of another. For example, the following command passes the standard output of Ps-aux to grep as input.

Ps-aux | grep httpd

Special characters in 4.shell

Like other programming languages, there are special characters in the shell. Common is the dollar sign ($), backslash (\), and quotation marks .

1. Dollar sign

The dollar sign represents a variable substitution , which replaces the variable with the value of the variable specified later. The backslash "\" is an escape character, and the escape character tells the shell not to treat the character that follows it specially , just as a normal character. The quotes under the shell are more complex and are divided into three types: double quotation marks ("), single quotation marks ('), and inverted quotation marks ('). Their roles are different, as described in one by one below.

2. Double quotation marks (")

characters enclosed in double quotation marks , except $, the inverted quotation mark ('), and the backslash (\) still retain their special functions, and the remaining characters are treated as ordinary characters nonspacing.

3. Single quotation mark (')

The character nonalphanumeric enclosed by single quotation marks appears as normal characters.

4. Inverted quotation marks (')

The quoted string is interpreted by the shell as the command line , and at execution time, theShell executes the command and replaces the entire quotation mark with its standard output .

The code and output for example 1 are as follows:

#echo "My current directory was ' pwd ' and logname is $LOGNAME" "double quotation marks and dollar signs keep the original function"

My current directory was /root and logname is root

The code and output for example 2 are as follows:

#echo "My current directory is ' pwd ' and logname are \ $LOGNAME" "Escape characters in double quotes keep the original function"

My current directory is /root and logname are $LOGNAME

The code and output for example 3 are as follows:

#echo ' My current directory was ' pwd ' and logname is $LOGNAME ' "The contents of the single quotation mark are unchanged"

My current directory was ' pwd 'and logname is $LOGNAME

5. Comments for Shell scripts

Shell scripts, like other programming languages, have annotations as well. The comment method is to add the # sign before the comment line.

For example, the following script:

[Plain]View PlainCopy
    1. #!/bin/sh
    2. #Filename: comment.sh
    3. #Description: This script explains what to make a comment
    4. echo "This script explains what to make a comment"

When you create a script, the first line of the script is often called a Shbang (#!) line. When the script starts, the UNIX kernel examines the first line of the file to determine which type of program will be executed.

The path behind the Shbang symbol (#!) is the shell location used to interpret this script. To use this feature correctly, #! Must be the first two characters in the file. If

This attribute is ignored when the file header has a space character or a blank line, and the line is interpreted as a normal comment line.

6. The function of the shell script after the comment-F

I've seen this before:

[Plain]View PlainCopy
    1. #!/bin/csh-f
    2. #Filename: comment.sh
    3. #Description: This script explains what to make a comment
    4. echo "This script explains what to make a comment"

Commonly referred to as the Quick Start option, the-f switch notifies the shell to not load the. cshrc file when it starts.

For ksh its Shbang line may be!/bin/ksh-p

For bash May!/bin/bash--noprofile
Operators in 7.shell scripts

Example:

Shell Programming Basics

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.