[i] write the first Shell script

Source: Internet
Author: User
Tags configuration settings echo command shebang

What is a Shell script?

The simplest explanation is that a shell script is a file that contains a series of commands. The shell reads the file and executes all the commands in the file as if the commands were entered directly into the command line.

The Shell is unique because it is not only a powerful command-line interface, but also a scripting language interpreter. As we'll see, most of the tasks that can be done on the command line can also be implemented with a script, and in the same way, most of the operations that can be implemented with scripting can be done on the command line.

While we've covered many shell features, we're only focusing on features that are often used directly on the command line. The Shell also provides some functionality that is usually (but not always) used when writing programs.

How to write a Shell script

To successfully create and run a shell script, we need to do three things:

    1. Write a script. A Shell script is an ordinary text file. So we need a text editor to write them. The best text editor will support syntax highlighting so that we can see a color coded view of a script keyword. Syntax highlighting helps us see some common mistakes. In order to write script files, vim,gedit,kate, and many other editors are good candidates.

    2. Make the script file executable. The system will be pretty picky not to allow any old text files to be seen as a program, and for good reason! So we need to set permissions on the script file to allow it to execute.

    3. Place the script where the shell can find it. When no executable path name is specified, the shell automatically searches for some directories to find the executable file. For maximum convenience, we will place the script in these directories.

script file Format

To preserve the programming tradition, we will create a "Hello World" program to illustrate an extremely simple script. So let's start our text editor and enter the following script:

#!/bin/is'Hello world! '

For the last line in the script, we should be quite familiar, just a echo command with a string parameter. It is also familiar to the second line. It looks like a comment that we've seen in many of the configuration files we've checked and edited. For comments in shell scripts, they can also appear at the end of a line of text, like this:

' Hello world! '  is a comment too

All characters after the # symbol are ignored in the line of text.

Similar to many commands, this also works on the command line:

' Hello world! '  is a comment Toohelloworld!

Although annotations are rarely used on the command line, they can also work.

The first line of text in our script is a bit cryptic. It looks like it should be a comment because it starts with a # symbol, but it seems so meaningful that it's not just a comment. In fact, this #! character sequence is a special structure called shebang. This shebang is used to tell the operating system the name of the interpreter used to execute this script. Each shell script should take this line of text as its first row.

Let's save this script file as Hello_world.

Executable Permissions

The next thing we want to do is make our script executable. With the chmod command, this is easy to do:

 [[email protected]~]$ ls-l hello_world -rw-r--r--1  vforbox vforbox 63  2016 -
    02 -
    10 : 
     hello_world[[email protected]  ~]$ chmod 
      hello_world[[email protected]  ~]$ ls-      l hello_world -rwxr-xr-x 1  vforbox Vfobox 63  2016 - 02 - : 10  Hello_world 

For script files, there are two common permission settings, and a script with a permission of 755, everyone can execute, and a script with a permission of 700, only the file owner can execute. Note to be able to execute the script, the script must be readable.

Script File Location

Once the script permissions have been set, we can execute our script:

To be able to run this script, we must specify a clear path to the script file. If we don't do that, we'll get a hint like this:

[Email protected]~]$ hello_worldbash:hello_world:command not found

Why is that? What makes our scripts different from other programs? As it turns out, there's nothing. There is no problem with our script. is a problem with the location of the script store. The PATH environment variable and its role in finding executable programs in the system. If no explicit pathname to the executable is given, the system searches a series of directories each time to find the executable program. This/bin directory is the directory where one of the systems automatically searches. This directory list is stored in an environment variable named PATH. This PATH variable contains a list of directories separated by colons. We can view the contents of PATH:

[Email protected]~]$ echo $PATH/home/vforbox/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/ sbin:

Here we see a list of our catalogs. If our script is stationed in any directory on this list, then our problem will be resolved. Note The first directory in the list,/home/vforbox/bin. Most Linux distributions Configure the PATH variable to include a bin directory in the user's home directory, allowing users to execute their own programs. So if we create a bin directory and put our script in this directory, then the script should start working like any other program:

[Email protected]~]$ mkdir bin[[email protected]~]$ mv Hello_world bin[[email protected]~]$ Hello_worldhelloWorld!

It does work.

If this PATH variable does not contain this directory, we can easily add it by including the following line of text in our. bashrc file:

Export Path=~/bin:"$PATH"

Once this modification is made, it will take effect in each new terminal session. In order to apply this modification to the current Terminal session, we must have the shell re-read the. bashrc file. This can be done through the "sourcing". bashrc file:

[Email protected]~]$. . BASHRC

This point (.) command is a synonym for the source command, a shell internal command that reads a specified shell command file and sees it as input from the keyboard.

Note: In Ubuntu systems, if there is a ~/bin directory, Ubuntu automatically adds the ~/bin directory to the PATH variable when the user's. bashrc file is executed. So in Ubuntu system, if we create this ~/bin directory, then exit and then log in, everything will work.

A good place to script files

This ~/bin directory is a good place to store scripts for personal use. If we write a script that can be used by every user in the system, the traditional location of this script is/usr/local/bin. The scripts used by system administrators are often placed in the/usr/local/sbin directory. In most cases, locally supported software, whether scripted or compiled, should be placed in the/usr/local directory instead of in the/bin or/usr/bin directory. These directories are specified by the Linux file system hierarchy Standard and contain only the files that are provided and maintained by the Linux Publisher.

More formatting Tips

Serious script writing, a key goal is to maintain convenience, that is, a script can be easily modified by the author or other users, so that it adapt to the changing needs. Making scripts easy to read and understand is a convenient way to maintain.

Indent and line continuation characters

When hiring a long command, you can improve the readability of your commands by expanding them in several lines of text.

0600 -06000711 -0711 ' {} '; ')

Obviously, this command is a bit difficult to understand, when the first sight of it. In the script, this command may be easier to understand, if you write it like this:

Find Playground     \ (         -type F         0600         0600  ' {} '; '     ) \)     -or     \ (         -type D         0711         0711  ' {} '; '     \)

By using the line continuation character (backslash-carriage sequence) and indentation, the logic of this complex command is more clearly described to the reader. This technique also takes effect on the command line, although it is seldom used because it is cumbersome to enter and edit this command. One difference between the script and the command line is that the script may employ the tab character Vlasov to implement indentation, but the command line is not, because tab characters are used to activate auto-completion.

Configuring Vim for writing scripts

This vim text editor has many configuration settings. There are several common options that can help script writing:

: Syntax on

Turn on syntax highlighting. With this setting, different shell syntax elements are displayed in different colors when the script is viewed. This is useful for identifying certain programming errors. And it looks cool too. Note that for this function to work, you must have a full Vim version installed, and the file you are editing must have a shebang to indicate that the file is a shell script. If you're having trouble with the above command, try this: set Syntax=sh.

: Set Hlsearch

This option is turned on in order to highlight the search results. Let's say we look for the word "echo". By setting this option, each instance of the word is highlighted.

: Set tabstop=4

Sets the number of columns that a tab character occupies. The default is 8 columns. Setting this value to 4 (a common practice) makes it easier for long text lines to adapt to the screen.

: Set Autoindent

Turn on the "Auto indent" feature. This results in vim being able to indent the new line of text with the same number of columns as the text line that was just entered. For many programming constructs, this accelerates the input. Stop indenting and enter ctrl-d.

These changes will take effect permanently by adding these commands (without the colon character at the beginning) to your ~/.VIMRC file.

Summarize and generalize

In the first chapter of this script, we've seen how to write scripts and how to make them easy to execute in our system. We also know how to use various formatting techniques to improve the readability (maintainability) of the script. In later chapters, easy Maintenance will appear as a central rule for writing scripts over and over again.

[i] write the first Shell script

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.