Bash Scripting: Creation Guide

Bash scripting scripts are used by system administrators, programmers, network engineers, scientists, and almost everyone who regularly uses the Linux / Unix system. No matter what the user does and what their general level of computer proficiency is, they can find a way to use Bash scripting for themselves. Although correct, they are called shell scripts, but most programmers call them Bash scripts.

As an interactive shell, it is a short language for initiating and managing calculations. As a scripting language, it is a domain-specific language for managing and linking processes and files.

Bash Script Definition

Bash scripting is a command language interpreter. It is widely available on various operating systems and is the default command analyzer for most GNU / Linux systems. This is the abbreviation "Bourne Again SHell."

Other definitions:

  1. Shell is a macro processor that allows interactive or non-interactive command execution.
  2. Scripting allows you to configure the automatic execution of commands that would otherwise act interactively one after another.

Bash scripting is installed by default on many GNU / Linux systems, so the shell script works even without defining it as an interpreter. To find out what the default command executes, prescribe:

$ echo $ SHELL / bin / bash.

There are other shell interpreters such as Korn, C, and many others. For this reason, it is recommended that you define a shell interpreter that will be used specifically for the contents of the script.





Shell interpreter




Now all scripts will include the shell interpreter definition: #! / Bin / bash.

More specifically, this is written in the special literature Advanced Bash scripting guide.

File Names and Permissions

To execute a shell script, the file must be executable, executed using the “chmod + x FILENAME” command. By default, any newly created files are not executed regardless of the file extension suffix. In fact, the latter property on GNU / Linux systems is basically irrelevant.

When executing the “ls” command to list all files and directories, it immediately becomes clear that a file with the extension “.sh” is a plausible shell script, and with “.jpg” it will be a compressed image. For more information on the file extension for this language, see the Advanced Bash scripting guide tutorials.

On GNU / Linux systems, the command can be used to identify the type of file. As you can see from the example below, the file extension does not matter, and the shell interpreter in this case has more weight.

On GNU / Linux systems file




Thus, the shell script name “0_xyz” works fine, although programmers try to avoid it whenever possible.





PATH shell command

PATH shell command




When a developer enters a command into a shell, Bash looks in certain directories to see if he can find it. Therefore, according to the Bash scripting guide, if they type “ls” in the shell, it will only execute the command if it is in its path. The operation will fail if it is not in one of the directories that are part of the route. If there is a match in more than one of the directories on the path, he selects the first. You can find out the route by running:

echo $ PATH.

Something like this will appear on the monitor screen:

/ home / jzb / bin: / usr / local / bin: / usr / bin: / bin: / usr / bin / X11: / usr / X11R6 / bin: / usr / games: / usr / lib / jvm / jre / bin

The correct home directory path

Each directory that Bash looks in is separated by a colon. In this case, the “bin” directory will be checked first of them, and then / usr / local / bin, / usr / bin.

If the user is logged in as root, he should see a different set of directories, including / usr / local / sbin, / usr / sbin.

You can add them to the path or change it by editing the files:

~ / .bashrc and ~ / .bash_profile.

For example: PATH = "$ HOME / bin: $ PATH".

You can slightly modify this rule and install advanced Bash scripting. PATH "=" tells Bash that he will set the path, and $ HOME / bin prompts him to add the bin directory, and after $ PATH recommends that he add everything that is already on the route.

The “:” parameter is a separator between elements. The developer will see something like this on the screen of his monitor:

if [-d "$ HOME / bin"];

then PATH = "$ HOME / bin: $ PATH"

fi.

This rule will check if the “bin” directory exists in the home directory, and then add it to the path in order to correctly execute the “run Bash script” operation.

Lowercase alias

An alias is a string in which Bash will be replaced by another command. A simple example:

alias ls = 'ls --color = auto'.

This tells him that when “ls” is started, “ls --color = auto” must be started, without typing anything else. You can set aliases on the command line, and this is good for testing.

At the same time, it makes sense to set aliases to “~ / .bash_profile and ~ / .bashrc”. Or create something like “~ / .aliases” and call it from the configuration files as follows:

if [-f ~ / .bash_aliases];

then. ~ / .bash_aliases

fi

To see existing aliases, just run it in the shell. It is listed by default in the distribution. Here, for example, is the default set installed on openSUSE 11.2, without any changes.

Lowercase alias




As a test, you can see what is already installed by the distribution, and try to make some of your own options.

Shell extension

Shell extension




Before Bash executes the command, it evaluates the input and “expands” the aliases and other expressions whenever necessary. It has several characters that it necessarily expands to match one or more characters, and they are called “wildcards”. Such pattern matching can be really useful.

For example, if you want to see all JPEG files in a directory, start “ls * jpg”, provided that the JPEG files are marked as “jpg” and Bash will expand this to match any file name that ends with jpg.

If you want to combine only 1 character, use "?". This will point to one character, so “ls? .Jpg "will only match file names, for example," 1.jpg "or" a.jpg ", not" 01.jpg ".

Bash also allows you to match ranges of characters using parentheses. Using [abc12] will match one of the characters when expanded. So, working “ls -lh [abc12] .jpg”, will correlate with a.jpg, b.jpg, c.jpg, 1.jpg and 2.jpg, but not 12.jpg or abc.jpg. You can negate the pattern by prefixing “bang” (!), For example: ls -lh [! Ab12] .jpg will match c.jpg or 3.jpg, but not 2.jpg, etc.

Another convenient trick is the expansion of the bracket, when you need to organize documents by year and date. If, for example, in the ~ / Documents folder there is a 2010 directory with subdirectories from 01 to 12 and you do not need to print from 01 to 12, do Bash instead: mkdir 2010 / {01..12}. When he reads the rule, he expands what is in braces from 01 to 12. This also works with letters, so if you need subdirectories via z, you can run mkdir {a..z} and he will create directories through z . May also work with capital letters.

Script execution

There is an alternative way to run Bash scripts. In a very simplified view, its script is nothing more than a text file containing instructions that must be executed in order from top to bottom. How the instructions are interpreted depends on the specific shebang or script execution method.

Script execution




Another scripting method is to explicitly call its interpreter, for example, $ bash date.sh. Therefore, the script will be executed without having to run a shell script and without declaring a shebang directly in the operating system schema, invoking the bash binary executable. Thus, the contents of the date.sh file will be loaded and interpreted as Bash Shell Script.

Relative and absolute path

Before programming the official shell script, for example, exit Bash script, you need to determine the navigation with it and set the difference between the relative and absolute path to the file. Probably the best analogy that explains the relative and absolute path to a file is to visualize the GNU / Linux file system as a multi-story building.

The root directory is the front door of the building, indicated by the position, it provides access to the entire file system of the "building", therefore, gives access to all directories - "floors" and "rooms" - and files - "residents". To, for example, go to room 1 on the 3rd floor, you first need to enter the main door, and then go to the 3rd floor (level3) and from there enter the room (room1). Therefore, the absolute path to this particular room on the floor inside the building is “/ level3 / room1”.

From here, if you need to visit room2 also at level 3, first fix the current location, which is room 1, by entering “../”, and then by including the name of the room “room2”. In this case, the relative path to room 2 is taken, which in this case is "../room2". Since in this example the user was already at the third level, he does not need to leave the entire building and re-pass the absolute path through the main entrance / level3 / room2.

Fortunately, GNU / Linux has a simple compass tool to help the programmer navigate the entire file system as a “pwd” command. This command will always print the current location when executed. The following example will use the “cd” and “pwd” command to navigate the GNU / Linux file system using absolute and relative paths.

Relative and absolute path




Further continued.

bash shell script




Execute the “cd” command without any arguments to instantly go to the user's home directory from anywhere. As you can see, navigating through the GNU / Linux file system is both a simple and at the same time very confusing topic.

The concept of variables

Almost every programming language has the concept of variables - a symbolic name for a part of memory to which you can assign values, read and manipulate its contents. For example, for the Bash script example, “Hello World” can be executed using variables. Please note that there should be no spaces around the "=" sign:

  • VAR = value works;
  • VAR = value does not work.

In the first case, the shell sees the symbol “=” and treats the command as a variable assignment. In the second case, the shell assumes that the VAR must be the name of the command and tries to execute it. Enter the following code in var.sh.

The concept of variables




This sets the variable "Hello World" to the variable MY_MESSAGE. In this case, quotes are needed around the Hello World string, and the variable can contain only 1 value, so the string with spaces should be quoted so that the shell knows that all this is considered as one. Otherwise, the shell will try to execute the World command after assigning MY_MESSAGE = Hello.

The shell is not demanding on the types of variables, they can store strings, integers, real numbers - all that the user likes. Experienced programmers pay attention to the fact that special characters must be properly escaped. To do this, use the shell-builtin, read command, which reads a string from standard input into the supplied variable. If you give it a full name and do not use double quotes around the "echo" command, it will still be displayed correctly.

Most languages ​​have the concept of loops, if you need to repeat the task twenty times, it is unlikely that the user wants to enter the code 20 times, and even, most likely, with errors. For this, there are “for” and “while” loops in the Bourne shell. This gives a few less opportunities than other languages, but no one claims that shell programming has the power of C. The for loop repeats through a set of values ​​until the list is exhausted, ghb 'njv values ​​can be any.

First script

First script




For the first shell script, you can simply write a script that says “Hello World”. Create the file (first.sh) as follows: first.sh The first line tells Unix that the file should be run / bin / sh. This is the standard shell layout for almost every Unix system.

If the Linux Bash script is used, then GNU / Linux / bin / sh is usually a symbolic link to bash, or dash has recently been used. The second line begins with the special character "#". This marks the line as a comment, and it is completely ignored by the shell. The only exception is when the first line of the “#!” File begins. This is a special directive that Unix considers especially and means that even if they use “csh”, “ksh” or something else as an interactive shell, then the subsequent one will be interpreted by Bourne.

Similarly, Perl can begin with the line:

#! / usr / bin / perl

This tells the interactive shell that the following command should be executed perl. For programming, Bourne shells typically follow:

#! / bin / sh.

The third line executes the "echo" command with two parameters or arguments: the first - "Hello"; the second is "World." Note that "echo" will automatically set one space between its parameters. The symbol still marks the comment "#", and all subsequent ones are ignored by the shell.

Test to test the script

Test for writing a script




The test is used for almost every written shell script. At the same time, “test” is not called so directly, the designation “[” is more often used. It is a symbolic link of the word to make shell programs more readable.

This usually means that the Bash shell script itself will be interpreted as “[” as the value “test”, even if the Unix environment is configured differently. This means that “[” is actually a program, like “ls” and others, so it should be surrounded by spaces: if [$ foo = "bar"] will not work, as this is interpreted as: if test $ foo = "bar"], which is "]" without the beginning of "[".

In this case, put spaces around all the operators and highlight the required ones with the word "SPACE", replacing it with the actual space, otherwise, if there is no space, this will not work:

if SPACE [SPACE "$ foo" SPACE = SPACE "bar" SPACE]

Some shells accept "==" to compare strings. For the latter, it is better to use a single "" or "-eq" for integers.

As you can see, the test is a simple but powerful comparison utility that is necessary for working in the shell.

Of course, everyone will not become a guru-bash at the end of reading the article, but they will be more confident and armed with the necessary knowledge and skills to easily do their job.




All Articles