GNULinux actual combat notes EMACS - Bash program design

zhaozj2021-02-16  47

[GNU / Emacs articles Linux actual notes of the --Bash programming] Author: Ye Weibin MSN: fritz_yea@hotmail.comCopyright (C) Free Software Library, Org (http://yea.xiloo.com) in accordance with article GNU Free Document Lience Release, anyone can copy the original, reproduced, but be sure to keep this statement. The author is not responsible for any result caused by this article.

7. After reading the simple shell program for the last time, we have to study the powerful programming capabilities of the shell. Shell is a programming language that is easy to learn, at least because it is easy to perform interactive tests respectively before combining each small program into a large program. With the modern UNIX operating system, we can write a fairly huge structured program. In the next few sections, we will learn: • Variables: strings, numbers, environment and parameters • Conditions: Boolean, Program Control in Shell: IF, Elif, For, While, UnTIL, CASE · Function · Notes

In order to ensure the stringency and interest of Bash programming, I directly reference the "Linux program design" of the Wrox Press, the second chapter of the second chapter of the second chapter. I want to learn the name, I should not be pirated here, at least its source code is based on GPL.

1. Variables in the shell, do not need to make a statement in advance before using variables. We can create and use variables directly at any need. By default, the variable type is a string, even if it saves a value. SHELL and some other tools automatically identify the "value" string and operate it according to the correct method. Variable names are case sensitive, which is consistent with UNIX systems. Therefore, variables var and var and var are different variables. The variable naming principle is the same as the principle of UNIX file naming, but no space is allowed, and it is more unable to reintegrate with existing system commands. In the shell, the variable name adds a "$" character in front, you can get its content. Just use the variable, we must add "$" in front of it, unless it is assigned. Assignment variables can be used directly, or the user's input will be assigned to the variable. Please see below: $ String = Hello $ Echo $ Stringhello $ String = "GUTEN TAG" $ STRINGGUTEN TAG $ STRING = 1 2 3 $ Echo $ String1 2 3 $ Read Stringi Love You / * User Enter, return end * / $ echo $ stringi love you / * read variable content * /

* Note that if you contain spaces in the string, you must enclose them with quotation marks. Also note that there is no space on both sides of the equal sign. ** I said that the numbers are also saved as a string, so the result of "String = 1 2 3" is still "1 2 3", not "6". *** Read reads the string input by the user to the end of the carriage return. 1.1, the usage of quotation marks is in general, and the parameters are separated by a blank character, such as a space, a tab or a newline, if you want to contain one or more such blank characters in one one parameter, The quotation marks must be added to the parameters. Quotation marks are also different. If you contain variables in double quotes, you will cause "name-value replacement", and it will not be in single quotes. We can also add "/" to "/" in "$" to cancel its special meaning. Let's take a look at the role of quotation marks in the variable output: #! / Bin / shmyvar = "hi there"

Echo $ Myvarecho "$ myvar" echo '$ myvar'echo / $ myvar

Echo Enter Some TextRevar

Echo '$ myvar' now Equals $ myvar

EXIT 0

The output result is:

Hi Therehi There $ Myvar $ Myvarenter Some Texthello World $ MyVar Now Equals Hello World

1.2, where the environment variable script is executed, some variables are initialized according to the system environment setting. These environment variables typically use uppercase to distinguish between user-defined variables, the latter typically use lowercase. Here are some common environment variables:

Environment Variable Description $ HOME Current User's login subdirectory $ PATH Separated by a colon Separate Subride list $ PS1 command line prompt, usually "$" character $ PS2 auxiliary prompt, used to prompt subsequent input , Usually a ">" character $ IFS input area separator. When the shell reads the input data, a set of characters will be used as a separated character between words, which is usually spaces, tabs, and newlines $ 0 shell script name $ # Parameters to the script. $$ The process ID of this shell scriptor, the script generally uses it to create a unique temporary file, such as / TMP / TMPFILE _ $$

1.3, Parameter Variable If your script has parameters when calling, you will generate additional variables. Even if you don't pass anything, "$ #" above still exists, but the value is 0.

Parameter Variable Description $ 1, $ 2 ... Script parameter $ * A list of all parameters, this is a separate variable, and the first character in each parameter is separated from the first character in the environment variable IFS $ @ "$" A variable of * ", it does not use IFS environment variables

Below is an example of using environment variables and parameter variables:

#! / bin / sh saltation = "Hello" Echo $ SALUTATIONECHO "The Program $ 0 is now Running" echo "The Second Parameter WAS $ 1" echo "The first parameter WAS $ 1" echo "the parameter list was $ *" echo "the User's Home Directory IS $ HOME "Echo" please enter a new greeting "Read Salutation

Echo $ SALUTATIONECHO "The Script is now completion"

EXIT 0

The output result is:

HelloThe program ./try_var is now runningThe second parameter was The first parameter was The parameter list was The user's home directory is / home / yeaPlease enter a new greetingSireSireThe script is now complete

2. Condition Test In actual work, most scripts use the "[]" or "TEST" command in the "[]" or "TEST" command. Note, "[]" and the space between the conditions to be checked. Because "[" and "Test" are actually the same, the "Test" command is subject to the space, so "[" will naturally have space. For the use of the "Test" command, please refer to the "Test" man page. I don't have to go out.

3. Control Structure - IF, Elif, For, While, UnTil, Case Shell has a range of control structures, and they are also similar to other programming languages. For some structures (such as a CASE statement), the shell provides a stronger function. In order to reduce the space, and let everyone look at it, I will directly list the grammatical structure and routines of each control structure, so that I don't add difficulty in understanding. 3.1, IF statement

IF ConditionThen StatementSelse Statementsfi

Example of the IF statement

#! / bin / sh

Echo "Is it Morning? please answer yes or no" read timeofDay

IF [$ TimeOfDay "=" YES "]; The echo" Good Morning "Else Echo" Good Afternoon "FI

EXIT 0

3.2, ELIF statement

IF ConditionThen StatementSelif ConditionThen StatementSelse Statementsfi

Example of an elif statement

#! / bin / sh

Echo "Is it Morning? please answer yes or no" read timeofDay

IF [$ TIMEOFDAY = "YES"] THEN Echo "Good Morning" Elif [$ TIMEOFDAY = "No"]; THEN Echo "Good afternoon" else echo "Sorry, $ TIMEOFDAY NOT Recognized. Enter Yes or no" exit 1fi

EXIT 0

3.3, for statement for Variable in Valuesdo StatementsDone

Example of a for statement

#! / bin / sh

For foo in bar ful 43do Echo $ FOODONE

EXIT 0

3.4, while, if we have to loop 100 times, you have to write from 1 to 100, so too tired. It does not have the convenience in Basic --for i = 1 to 100 Step 1, but it has its advantage, here is not talking. For the above situation, we can use the While structure and numerical replacement. While's grammatical structure is While ConditionDo StatementsDone

Look at the example below #! / Bin / sh

Foo = 1WHILE ["$ foo" --le 20] Do Echo "Here We Go AGAIN" foo = $ ($ foo 1)) DONE

EXIT 0

Here is shown in the $ (Command) structure.

3.5, unsil statements Until and while are very similar, just test the condition test. In other words, the loop will be repeated until the condition is really stop, not when the condition is true. Until's syntax for unsil conditiondo statementsdone

Example of a unchiL statement #! / bin / sh

Until Who | GREP "$ 1"> / dev / nulldo sleep 60done

# NOW RING The Bell and Announce The Unexpected User.

echo -e // aecho "***** $ 1 HAS JUST logged in *****"

EXIT 0

3.6, the CASE statement Case structure is slightly more complicated than the other statements you have seen in front. Its syntax is as follows: Case Variable In Patten [| Patten] ...) Statements ;; Patten [Patten] ...) Statements ;; ESAC

In fact, this grammatical structure is comparable to the Case structure we generally seen (such as a C / C Switch ~ Case structure), which can write multiple options (ie the optional part of []). It should be noted that the statement should be used to use two semicolons ";;" instead of a semicolon. In STATEMENTS, it can be a statement and can be several statements. The following is an example of several statements: #! / Bin / sh

Echo "Is it Morning? please answer yes or no" read timeofDay

Case "$ TIMEOFDAY" IN YES | Y | YES | YES) Echo "Good Morning" Echo "UP BRIGHT AND Early this Morning?" ;; [nn] *) Echo "Good aftern" ;; *) Echo "Sorry, Answer NOT RECognated "Echo" please answer yes or no "exit 1 ;; esac

EXIT 0

4. Function shell allows the user to define a function to include some system commands to form an execution module. In the shell, the function is very simple, write its name, plus a pair of empty "()", in a pair of curly bracket "{}", as follows: function_name () { The execution order of the Statements} shell script is the top down, so all the function declarations must appear before him execute, otherwise the shell will not find the function. 5. Comment Shell scripts use the "#" symbol to comment on the statement after it until the end. This is a bit like "//" comment in C . But all scripts, the first row is started by "#!" And specifies the program that executes this script. Here is another function of "#". This is only.

Eight, instance - MINI MUSIC JUKEBOX Using the basic elements above, we can build Bash scripts. In theory, Bash scripts can also write large, complex procedures. However, this is definitely not as high as C / C , Java and other compilation types. Our purpose of learning Bash is also to reduce the work efficiency of administrators by constructing the burden on system management by constructing shell scripts. So our goal is not a large program, but a short application of short dryness. I wrote the following things with BASH and used to play my music library. #! / bin / bash # this is very Simple Bash Script.it Just Help US Enjoy Music. # CopyRight (C) 2003, Free Software Library

# filename: Play_Music # to run this script, simply type follow command. # chmod x play_music # ./play_music

# This program is free software; you can redistribute it and / or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 2 of the License, or (at your # option) any Later Version.

# This program is distributed in the hopes that it will be useful, but # WITHOUT ANY WARRANTY;. Without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE See the GNU General # Public License for more details.

# G g '.

# The first thing to do is to ensure that some global variables that we'll be using # throughout the script are set up. We set the title and track files and a temporary file. # We also trap Ctrl-C, so our temporary File is removed if the user interrupts the script. # first, define some glope variables.choice = "" menu_choice = "quit = n

# SECOND, Define Some functions.add_mp3 () {echo "Add MP3 Files from $ home / music / mp3 to playlist file /" mp3list / "." Find $ homen / music / mp3 / -iname * .mp3 >> $ home / MUSIC / MP3LIST}

Add_ogg () {echo "Add Ogg Files from $ Home / Music / Oggg To Playlist File /" Ogglist / "." Find $ Home / Music / Ogg / -iname * .ogg >> $ homen / music / ogglist}

Play_mp3 () {Clear Echo "Playing MP3 files with mpg123." echo "control key:" echo "s => stop, p => pause, f => forward, b => backward, q = quit (directly) echo "Also" Echo "Press Ctrl-c for next song, And Press Ctrl-C Twice Withnin a Short While To Quit."

MPG123 -C --List $ homen / music / mp3list return}

Play_OGG () {Clear Echo "Playing Ogg Files with Ogg123." Echo "Control Key:" Echo "Press Ctrl-c for Next Song, And Press Ctrl-C Twice Withnin A Short While To Quit." Echo

Ogg123 $ homen / music / ogg # as the Ogg123 Do Not Support Playlist, We Never Use the oglist file. Return}

welcome_msg () {clear echo echo ". Mini Music Jukwbox - A very simple program written in Bash script" echo echo "Before using it, you should at least have the following two program on your system:" echo "ogg123 - needed for "echo" mpg123 - needed for playing mp3 files. "echo echo" do you have allse software? (y / n): "Read choice} set_menu () {Clear Echo" mini Music Jukwbox. "echo echo" Options: "Echo echo" 1) Add mp3 files to playlist "Echo" 2) Add Ogg Files to Playlist "Echo" 3) Play MP3 "Echo" 4) Play OGG "q) Quit" Echo Echo "please enter Your Choice and the press return "read menu_choice}

# Final, THE Application Properwelcome_msgif ["$ choice" = "y"] Then While ["$ qit"! = "Y"] do set_menu case "$ menu_choice" in 1) add_mp3 ;; 2) add_ogg ;; 3) Play_mp3 ;; 4) Play_ogg ;; q | q) quit = y ;; *) Echo "sorry, choice not recognized" ;; esac doneelse exit 0fi

echo "Thanks for useing. Bye! :)" EXIT 0

Run this script in Shell mode. I only use the partial features of Bash here, you can modify the above program as an experiment that learns Bash.

[GNU / Linux actual combat "EMACS] is over. This article only involves Bash, and does not involve Emacs, so you can see this article as an independent article describing Bash programming. But because we have always written and debug scripts in the environment of Emacs, I will still return him into the EMACS. In the next [Emacs of GNU / Linux actual combat, I will introduce how to customize the Emacs IDE environment, making it better. Let's see you next.

转载请注明原文地址:https://www.9cbs.com/read-26756.html

New Post(0)