Basic Shell learning and basic Shell Learning

Source: Internet
Author: User

Basic Shell learning and basic Shell Learning
Shell

Shell is a program written in C language, which serves as a bridge between users using Linux. Shell is both a command language and a programming language.

Shell is an application that provides an interface through which users can access the services of the operating system kernel.

Ken Thompson's sh is the first Unix Shell, and Windows Explorer is a typical GUI Shell.

Shell online tools

Shell script

Shell script is a script program written for shell.

The shell mentioned in the industry usually refers to shell scripts, but shell and shell script are two different concepts.

Shell Environment

Shell programming is the same as java and php programming.Text EditorAnd an interpreted executionScript interpreterYou can.

There are many Shell types in Linux, and common ones are:

Bourne Shell (/usr/bin/sh or/bin/sh) ------ Bash

Bourne Again Shell (/bin/bash)

C Shell (/usr/bin/csh)

K Shell (/usr/bin/ksh)

Shell for Root (/sbin/sh)

......

Bash is the default Shell for most Linux systems. In general, there is no distinction between the Bourne Shell and the Bourne Again Shell, so, like #! /Bin/sh, which can also be changed #! /Bin/bash.

#! Tell the system that the program specified in the subsequent path is the Shell program that interprets the script file.

First shell script

Open the Text Editor (you can use the vi/vim command to create a file) and create a file named test. sh: the extension is sh (sh stands for shell). The extension does not affect script execution. It is nice to know the name. If you use php to write a shell script, the extension will be used in php.

Enter some code. The first line is generally like this:

Instance #! /Bin/bash
Echo "Hello World! "
Running instance?

#! Is an agreed tag, which tells the system what interpreter is required to execute this script

There are two methods to run Shell scripts:

1. As an executable program

Save the above Code as test. sh and cd it to the corresponding directory:

Chmod + x./test. sh # grant the script execution permission./test. sh # execute the script

Note that you must write it as./test. sh insteadTest. shTo run other binary programs. Write test directly. sh, the linux system will go to the PATH to find whether it is named test. sh, and only/bin,/sbin,/usr/bin,/usr/sbin and so on in the PATH. Your current directory is usually not in the PATH, so it is written as test. sh cannot find the command. /test. sh tells the system to find it in the current directory.

2. As an interpreter Parameter

In this running mode, run the interpreter directly. The parameter is the name of the shell script file, for example:

/bin/sh test.sh/bin/php test.php

This method does not need to specify the interpreter information in the first line.

Shell variable

When defining a variable, the variable name does not contain a dollar sign ($, required for a variable in PHP), for example:

your_name="come"

Note that there is no space between the variable name and equal sign, which may be different from all programming languages you are familiar. Variable names must follow the following rules:

The name can only contain English letters, numbers, and underscores. The first character cannot start with a number.

There cannot be spaces in the middle, and you can use underscores (_).

Punctuation cannot be used.

You cannot use keywords in bash (you can use the help command to view reserved keywords ).

In addition to explicitly assigning values directly, you can also assign values to variables using statements, such:

for file in `ls /etc`

The preceding statement loops the file names in the/etc directory.

Use Variables

To use a defined variable, you only need to add a dollar sign before the variable name, such:

your_name="qinjx"echo $your_nameecho ${your_name}

The curly braces outside the variable name are optional and can be added without adding them. The curly braces are used to help the interpreter identify the boundary of the variable, for example:

for skill in Ada Coffe Action Java; do    echo "I am good at ${skill}Script"done

If you do not add curly brackets to the skill variable and write it as echo "I am good at $ skillScript", the interpreter regards $ skillScript as a variable (its value is null ), the code execution result is not what we expect.

We recommend that you add curly brackets to all variables.This is a good programming habit.

The Defined variables can be redefined, for example:

your_name="tom"echo $your_nameyour_name="alibaba"echo $your_name

This write method is legal, but note that $ your_name = "alibaba" cannot be written for the second value assignment. The dollar sign ($) is added when the variable is used ).

Read-Only variables

The readonly command can be used to define a variable as a read-only variable. The value of a read-only variable cannot be changed.

In the following example, an error is returned when you try to change the read-only variable:

#!/bin/bashmy="http"readonly myUrlmy="https"

Run the script. The result is as follows:

/bin/sh: NAME: This variable is read only.
Delete variable

You can use the unset command to delete variables. Syntax:

unset variable_name

Variables cannot be used again after they are deleted.The unset command cannot delete Read-Only variables.

Variable type

When running shell, there are three variables at the same time:

1) local variables are defined in scripts or commands and only valid in the current shell instance. Other programs started by shell cannot access local variables.

2) All programs with environment variables, including those started by shell, can access environment variables. Some programs require environment variables to ensure normal operation. When necessary, shell scripts can also define environment variables.

3) The shell variable is a special variable set by the shell program. Some shell variables are environment variables and some are local variables, which ensure the normal operation of shell.

Shell string

Strings are the most commonly used and useful data types in shell programming (except for numbers and strings, there are no other types of useful data). Strings can be enclosed in single quotation marks, double quotation marks, or no quotation marks. The difference between Single and Double quotation marks is similar to that in PHP.

Single quotes
str='this is a string'

Restrictions on single quotes:

Any character in single quotes is output as is, and the variable in single quotes is invalid;

Single quotes are not allowed in single quotes ).

Double quotation marks
your_name='qinjx'str="Hello, I know your are \"$your_name\"! \n"

Advantages of double quotation marks:

Variables can exist in double quotation marks.

Escape characters can appear in double quotation marks

Concatenated string
your_name="qinjx"greeting="hello, "$your_name" !"greeting_1="hello, ${your_name} !"echo $greeting $greeting_1
Returns the string length.
String = "abcd" echo $ {# string} # output 4
Extract substring

The following example truncates four characters from the string's 2nd characters:

String = "runoob is a great site" echo $ {string: 1: 4} # output unoo
Search for substrings

Find the location of the character "I or s:

String = "runoob is a great company" echo 'expr index "$ string" is '# output 8

Note: In the above script, "'" is a reverse quotation mark, not a single quotation mark "'".

Shell Array

Bash supports one-dimensional arrays (multidimensional arrays are not supported), and the array size is not limited.

Similar to the C language, the subscript of an array element starts from 0. To obtain the elements in an array, use the subscript. The subscript can be an integer or an arithmetic expression, and its value must be greater than or equal to 0.

Define an array

In Shell, brackets are used to represent arrays. array elements are separated by spaces. The general format of the defined array is:

Array name = (value 1 value 2... value n)

For example:

array_name=(value0 value1 value2 value3)

Or

array_name=(value0value1value2value3)

You can also separately define the components of the array:

array_name[0]=value0array_name[1]=value1array_name[n]=valuen

Continuous subscripts are not allowed, and the range of the subscripts is unlimited.

Read Array

The general format for reading array element values is:

$ {Array name [subscript]}

For example:

valuen=${array_name[n]}

You can use the @ symbol to obtain all elements in the array, for example:

echo ${array_name[@]}
Returns the length of an array.

The method for obtaining the length of an array is the same as that for obtaining the length of a string, for example:

# Obtaining the number of array elements length =$ {# array_name [@]} # Or length =$ {# array_name [*]} # obtaining the length of a single array element lengthn =$ {# array_name [n]}
Shell comment

The line starting with "#" is a comment and will be ignored by the interpreter.

Sh does not contain comments from multiple lines. Only one # sign can be added to each line.

What should I do if a large code segment needs to be commented out temporarily and the comment is canceled later?

Adding a # symbol to each line is too laborious. You can enclose the code to be annotated with a pair of curly brackets and define it as a function. This function is called everywhere, this code won't be executed, achieving the same effect as the annotation.

Entertainment decompression:
#! /Bin/bash #! /Bin/bash indicates searching in the current path # Usage: # indicates comments, and only one line of comments can be added. It doesn't matter if you enclose multiple rows in braces and do not call them.
# Set: Display existing shell variables in the system. set the variable's new variable value.-indicates to close; + indicates to open; set-x # x indicates to execute the command, the command is executed first and the set-e # e parameter indicates that if the return value of the command is not equal to 0, then immediately exit shellexport PYTHONUNBUFFERED = "True" # Set the environment variable GPU_ID = $1 # variable and value NET =22net_lc =$ {NET ,,} DATASET = $3 array = ($ @) len = $ {# array [@]} EXTRA_ARGS =$ {array [@]: 3: $ len} rows =$ {EXTRA_ARGS // _} case $ DATASET in pascal_voc) TRAIN_IMDB = "inline" TEST_IMDB = "voc_2007_test" PT_DIR = "pascal_voc" ITERS = 40000 ;; coco) TRAIN_IMDB = "coco_2014_train" TEST_IMDB = "coco_2014_minival" PT_DIR = "coco" ITERS = 280000; *) echo "No dataset given" exit ;; esacLOG = "experiments/logs/fast_rcnn_{{net}_{{extra_args_slug}.txt. 'date + '% Y-% m-% d _ % H-% M-% S' "exec &> (tee-a" $ LOG ") echo Logging output to "$ LOG" time. /tools/train_net.py -- gpu $ {GPU_ID} \ -- solver models/$ {PT_DIR}/$ {NET}/fast_rcnn/solver. prototxt \ -- weights data/imagenet_models/$ {NET }. v2.caffemodel \ -- imdb $ {TRAIN_IMDB} \ -- iters $ {ITERS }\$ {EXTRA_ARGS} set + xNET_FINAL = 'grep-B 1 "done solving" $ {LOG} | grep" wrote snapshot "| awk '{print $4}'' set-xtime. /tools/test_net.py -- gpu $ {GPU_ID} \ -- def models/$ {PT_DIR}/$ {NET}/fast_rcnn/test. prototxt \ -- net $ {NET_FINAL} \ -- imdb $ {TEST_IMDB }\$ {EXTRA_ARGS}
Read it after reading it!

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.