Bash Shell Learning notes (i)--common commands

Source: Internet
Author: User
Tags echo command parent directory


One, the basic Bash Shell command 1, the default bash shell prompt is the dollar sign ($); 2. The Bash manual uses the man command to access the manual pages stored on the Linux system, such as:

Bogon:~ mac$ man Kill

KILL (1) BSD General Commands Manual KILL (1)

NAME

Kill --terminate or signal a process

Synopsis

Kill [-s signal_name] pid ...

Kill - L [exit_status]

Kill - signal_name pid ...

Kill - signal_number pid ...

DESCRIPTION

The kill utility sends a signal to the processes specified by the PID op-

Erands.

Only the super-user could send signals to other users ' processes.

The options are as follows:

- S Signal_name

A symbolic signal name specifying the signal to be sent instead

of the default term.

Search the man page with keywords
syntax: man-k keyword
For example: Find commands related to terminal commands, you can enter Man-k terminal3, common Linux directory name 4, directory knowledge
    • A single-dot character (.), which indicates the current directory;
    • A double-dot character, (..), that represents the parent directory of the current directory.
    • ls command to display files and directories in the current directory
      • The-f parameter adds a forward slash (/) after the directory name to make it easier for the user to distinguish them in the output, such as:

Bogon:users mac$ ls-f

guest/ mac/ shared/

    • The-r parameter is another parameter that is available for the LS command, called a recursive option. It lists the files in subdirectories that are contained in the current directory.
    • To display hidden files and common files and directories, you need to use the-a parameter.
    • The commonly used parameter is-L. The-l parameter produces a long tabular output that contains more information about each file in the directory.

bogon:users mac$ ls-la

total 0

drwxr-xr-x   6 root   admin    204 Jul 10:08.

drwxr-xr-x  root   wheel   1156 Oct 13:36:

-rw-r--r--  1 root   wheel      0 Jul 31  pan>

drwxr-xr-x+ guest  _guest   408 Feb 27  Guest

drwxr-xr-x+ the mac    staff   1326 Oct, 10:28 Mac

drwxrwxrwt  Root   wheel    680 Oct 16:52 shared 

    • Description
      • File types, such as directory (d), file (-), character file (c), or block device (b);
      • The permissions of the file;
      • The total number of hard links to the file;
      • The user name of the file owner;
      • The group name of the file group;
      • The size of the file (in bytes);
      • The last modified time of the file;
      • The file name or directory name.
    • Question mark (?) Represents a character;
    • An asterisk (*) represents 0 or more characters.

$ ls-l my_scr?pt

-rw-rw-r--1 Christine Christine 0 may 13:25 My_scrapt
-rwxrw-r--1 Christine Christine 11:26 My_script
$

$ ls-l my*
-rw-rw-r--1 Christine Christine 0 may 13:25 my_file

-rw-rw-r--1 Christine Chr Istine 0 13:25 my_scrapt

-rwxrw-r--1 Christine Christine Si may 11:26 my_script

$ ls-l my_s*t
-rw-rw-r--1 Christine Christine 0 may 13:25 my_scrapt

-rwxrw-r--1 Christine Christine Ay 11:26 my_script

$ ls-l my_scr[ai]pt
-rw-rw-r--1 Christine Christine 0 may 13:25 my_s Crapt

-rwxrw-r--1 Christine Christine 11:26 my_script

$ ls-l f[a-i]ll
-rw-r w-r--1 Christine Christine 0 may 13:44 fall

-rw-rw-r--1 Christine Christine 0 could be 13:44 fell

-rw-r w-r--1 Christine Christine 0 may 13:44 fill

$ ls-l F[!a]ll
-rw-rw-r--1 Christine Christine 0 may 13:44 fell

-rw-rw-r--1 Christine Christine 0 may 13:44 fill

-rw-rw-r--1 Christine Christine 0 13:44 full

$

5. Create File:
    • Create an empty folder: $touch Test_one
    • Copying files: $CP-I source destination
      • When both the source and destination parameters are file names, the CP command copies the sources into a new file, named destination, and-I to indicate whether the destination file is overwritten when it exists.
    • TAB Auto Completion: The command CP really is entered, and the shell will automatically replenish the remaining filenames by pressing the TAB key!
    • To view the inode number of a file or directory, you can add the-i parameter to the LS command.
    • Move (aka Rename file):

      $ mv/home/christine/pictures/fzll/home/christine/fall

    • Remove: When using the RM command, develop a good habit of always adding the-I parameter.
6. Create and delete directories:
    • With the mkdir command, you can: $ mkdir new_dir
    • The basic command to delete a directory is rmdir. By default, the RmDir command removes only empty directories.
    • The ultimate Dafa to delete a directory and all its contents in one breath is to use the RM command with the-R parameter and the-f parameter, without prompting, all caution.
$ rm-rf Small_dir

7. View the contents of the file

    • To view the file type, document command

$ file My_file my_file:ascii text

$

    • View entire file: The Cat command is a powerful tool for displaying all the data in a text file.
      • The-n parameter adds a line number to all rows.

$ cat-n Test1

1 Hello

2

3 This is a test file.

4

5

6 that we'll use to test the cat command.

$

    • If you want to add line numbers only to lines that have text, you can use the-b parameter.
    • If you do not want tabs to appear, you can use the-t parameter. The-t parameter will be combined with the ^i character to replace the ownership table in the article.
    • The main flaw with the Cat command is that once you run it, you can't control what's behind it. To solve this problem, the developer wrote the more command. The more command displays the contents of the text file, but stops after each page of data is displayed.
    • The name of the less command is actually a word game (derived from the saying "less was more"), which is an upgraded version of the more command. Displays the file text of one screen at a time. It provides some very useful features that enable you to turn back and forth in a text file, and there are some advanced search features.
    • The tail command displays the contents of the last few lines of the file (the "tail" of the file). By default, it displays the 10 lines at the end of the file.
      • You can add the-n parameter to the tail command to modify the number of rows displayed. By adding-N 2, the tail command displays only the last two lines of the file:
$ tail-n 2 log_fileline19last line-line20$
    • The head command displays the contents of those lines at the beginning of the file. It also supports the-n parameter so that you can specify what you want to display.
Second, more bash shell command 1, probing process: The PS command can output a lot of information on all programs running on the system.  It can only display information at a specific point in time. The-e parameter specifies that all processes running on the system are displayed; the-f parameter expands the output, and the columns of these extensions contain useful information.
    • UID: The user who initiated these processes.
    • PID: Process ID of the process.
    • PPID: The process number of the parent process (if the process was started by another process).
    • C: CPU utilization in the process life cycle.
    • Stime: The system time at the start of the process.
    • TTY: A terminal device at the start of a process.
    • Time: The cumulative CPU times required to run the process.
    • CMD: The name of the program to start.
2, real-time monitoring process: The top command is similar to the PS command to display process information, but it is displayed in real time.
    • PID: ID of the process.
    • USER: The name of the process owner.
    • PR: The priority of the process.
    • NI: The value of the humility of the process.
    • VIRT: The total amount of virtual memory that the process consumes.
    • RES: The total amount of physical memory that the process occupies.
    • SHR: The total amount of memory shared by processes and other processes.
    • S: The state of the process (d stands for interruptible sleep state, R stands in the running state, s represents the sleep state, T represents the tracking state or stop state, and Z represents the rigid state).
    • %CPU: The percentage of CPU time used by the process.
    • %MEM: The amount of memory used by the process as a percentage of available memory.
    • Time+: The total amount of CPU time since the process started so far.
    • Command: The name of the line that the process corresponds to, that is, the program name that is started.
3. End process: The KILL command can signal the process through the process ID (PID), only with the PID of the process and not with the command

To send a process signal, you are the owner of the process or log on as the root user.

$ kill 3940-bash:kill: (3940)-Operation not permitted$
The Killall command is very powerful, and it supports ending a process with a process name rather than a PID. The Killall command also supports wildcard characters, which can be useful when the system becomes slow due to heavy load.
$ killall http*$
The command in the previous example ends all processes that begin with HTTP, such as the httpd service of the Apache Web server. Warning: When logging into the system as root, use the Killall command with special care because it is easy to misuse wildcards and end important system processes. This may corrupt the file system. 4. Processing data files
    • Sort data:
      • The sort command sorts the data rows in the text file according to the collation of the default language specified by the session.
      • Available with the-n parameter, which tells the sort command to recognize numbers as numbers instead of characters and sort by value
      • Another common parameter is-m, sorted by month.
      • The-K and-t parameters are useful when sorting data separated by fields, such as the/etc/passwd file. You can use the-t parameter to specify the field delimiter, and then use the-K parameter to specify the sorted field.
$ Sort-t ': '-K 3-n/etc/passwdroot:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/sbin/nologindaemon:x:2:2: daemon:/sbin:/sbin/nologin$
    • Search data: Use the grep command to help you find it. The command line format for the grep command is as follows.
$ grep [options] pattern [file]
      • If you want to reverse-search (output rows that do not match the pattern), you can add the-v parameter.
      • If you want to display the line number of the row that matches the pattern, you can add the-n parameter.
      • If you only know how many rows contain matching patterns, you can use the-c parameter.
      • If you want to set multiple patterns, you can use the-e parameter to set each pattern.
$ grep-e t-e F file1    -    three    four

$
5. Compressing data

Gzip is the most popular compression tool on Linux.

    • Gzip: Used to compress files.
    • Gzcat: Used to view the contents of a compressed text file.
    • Gunzip: Used to extract files.

$ gzip Myprog

$ ls-l my*

-rwxrwxr-x 1 Rich 2197 2007-09-13 11:29 myprog.gz
$

6. Archive data

The tar command was initially used to write files to a tape device, but it could also write output to a file, a usage that has been widely used on Linux to archive data.

Format of the tar command: tar function [options] object1 object2 ...

The function parameter defines what the tar command should do, as shown in table 4-8.

Each feature is available with options to define a specific behavior for the TAR archive file. Table 4-9 lists the common options that can be used with the tar command in these options.

After you download the open source software, you will often see the file name ending with. tgz. These are gzip compressed tar files that can be decompressed using the command TAR-ZXVF filename.tgz.

Third, understand the shell four, the use of Linux environment variable system environment variables are basically using all uppercase letters to distinguish from the normal user environment variables. To view global variables, you can use the ENV or PRINTENV command. In the echo command, adding $ in front of the variable name is more than just displaying the current value of the variable. It allows variables to be used as command-line arguments. It is important that there are no spaces between the variable name, equal sign, and value. If you created a local variable or shell script yourself, use lowercase letters. The root user account is the administrator of the Linux system, and the UID assigned to it is 0. Using File permission characters
    • -Representative documents
    • D Stands for Directory
    • L representative Link
    • C stands for the character type device? b Represents a block device
    • n represents a network device followed by 3 groups of three-character encodings. Each group defines 3 types of access rights:
    • R means that the object is readable
    • W indicates that the object is writable
    • X means that the object is executable if there is no permission, a single break will appear in that permission bit. These 3 groups of permissions correspond to the 3 security levels of the object:?
? The owner of the object? The genus group of the object? System other users   change permissions The chmod command is used to change the security settings for files and directories. The format of the command is as follows: chmod the symbol followed by options mode file indicates whether you want to add permissions (+) on top of existing permissions, or remove permissions (-?) on the basis of existing permissions, or set permissions to the following values (=). X: If the object is a directory or it already has execute permissions, give execute permission. S: Reset UID or GID at runtime. T: Keep files or directories. U: Set permissions to be the same as the owner. G: Set permissions to belong to the same group. O: Set permissions to be the same as other users. The  vim editor has two modes of operation: Normal mode? Insert mode when you first open the file you want to edit (or create a new file), the Vim editor enters normal mode. In normal mode, the Vim editor interprets keystrokes as commands (more discussed later in this chapter). In insert mode, VIM inserts each key you enter at the current cursor position into the buffer. Press the I key to enter insert mode. To exit the insert mode back to normal mode, press the Exit key (ESC, which is the escape key) on the keyboard. In normal mode, you can use the arrow keys to move the cursor around the text area (as long as Vim correctly identifies your terminal type). If you happen to be in a weird terminal connection that doesn't have a directional key defined, it's not completely hopeless. There are commands in vim to move the cursor. H: Move one character to the left. J: Move down one line (the next line in the text). K: Move up one line (the previous line in the text).? L: Move one character to the right. Moving back and forth in a large text file is especially troublesome, but Vim provides some commands to improve the speed of the move. Ctrl+f: Turn down one screen. Ctrl+b: Turn one screen on. G: Move to the last line of the buffer. Num G: Moves to the first NUM line in the buffer. GG: Moves to the first row of the buffer. The VIM editor has a special function in normal mode called command line mode. The command-line mode provides an interactive command line that allows you to enter additional commands to control the behavior of vim. To enter command-line mode, press the colon key in normal mode. The cursor moves to the message line, and a colon appears, waiting for the command to be entered. In command-line mode, there are several commands to save the buffer data to a file and exit vim. Q: If the buffer data is not modified, exit. q!: Cancels all modifications to the buffer data and exits. W FileName: Save the file to another file. WQ: Saves the buffer data to a file and exits. Each time the   variable is referenced, it outputs the value currently assigned to it. It is important to remember that the leadA dollar character is required when you use a variable value, and you do not use a dollar symbol when referencing a variable to assign it.   The most basic redirect sends the output of the command to a file. Bash Shell uses the greater than sign (>) to do this: command > outputfile can append data with double greater than sign (>>). The input redirection symbol is the less than sign (<) &NBSP;WC command to count the text in the data. By default, it outputs 3 values:? The number of lines of text? Number of words in text 8?  command1 | The Command2linux system actually runs both commands at the same time, connecting them within the system. As soon as the first command produces the output, the output is immediately sent to the second command. The data transfer does not use any intermediate files or buffers. bytes of text   when assigning a mathematical result to a variable, you can enclose the mathematical expression in dollar and square brackets ($[operation]). $ var2=$[$var 1 * 2] $ echo $var 2  using BC in scripts: The best way is to use inline input redirection, which allows you to redirect data directly on the command line. In a shell script, you can assign the output to a variable. variable=$ (BC << EOF Options Statements expressionseof) Example: #!/bin/bashvar1=10.46 var2=43.67 var3=33.2 VAR4=71VAR5 =$ (BC << EOF scale = 4 A1 = ($var 1 * $var 2) B1 = ($var 3 * $var 4) A1 + B1 EOF) echo the final answer for this mess I s $var 5  exit script: Each command running in the shell uses the exit status code to tell the shell that it has finished running. The exit status code is an integer value of 0~255 that is passed to the shell by the command at the end of the command run. This value can be captured and used in the script. Linux provides a special variable $ to save the exit status code of the last executed command. By convention, the exit status code for a successful end command is 0. Exit command: The Exit command allows you to specify an exit status code at the end of the script.   The most basic structured command is the If-then statement. The If-then statement has the following format. If command theNcommandsfi if Command1thencommand set 1elif command2thencommand set 2elif Command3thencommand set 3elif Command4thencommand set 4fi  Remember that in elif statements, the Else statement immediately following it belongs to the ELIF code block. They are not part of the previous If-then code block. The  bash shell provides another conditional test method that does not need to declare the test command in the If-then statement. If [condition]THENCOMMANDSFI square brackets define the test condition. Note that you must add a space before the first square bracket and the second square bracket, or you will get an error. The test command can be used to determine three types of conditions:? Numeric comparison? string comparison

The format of the double parenthesis command is as follows:

(expression) The format of the two-side brackets command is as follows: [[The Expression]]case command takes a list format to examine multiple values for a single variable.] Case Variable Inpattern1 | Pattern 2) commands1;; PATTERN3) commands2;; *) default commands;; Esac bash the basic format of the for command in the shell. The for VAR in list docommandsdone environment variable IFS, called the internal field delimiter (internal field separator). If you set a newline character as a delimiter: ifs=$ ' \ n '  c for Command format for ((variable assignment; condition; iteration process)) such as: for ((a = 1; a < 10; a++) Note that some parts have a for command for the bash shell: variables can have spaces, variables in the condition do not start with a dollar symbol, and the formulas for the iteration process are not formatted with the expr command. $ cat Test8 #!/bin/bash # Testing the C-style for Loopfor ((i=1; I <=, i++)) Doecho "The next number is $i" done$ ./test8 the next number is 1 the next number is 2 the next number is 3 the next number is 4 the next number is 5 the next Number is 6 The next # is 7 the next # is 8 the next # is 9 the next # is $  multivariable $ cat test9#!/b in/bash# multiple Variablesfor ((A=1, b=10; a <=; a++, b--)) Doecho "$a-$b" done$./test91-102-93-84-75-66-57- The basic format for the 48-39-210-1$ while command is: while TEST command doother commandsdone  Stop the running command:ctrl+c  special variable $ #含有脚本运行时携带的命令行参数的个数. When there are no arguments on the command line, the $ #的值为0, the value of the params variable is the same, but the ${!#} variable returns the script used by the command line. The  $* variable saves all arguments provided on the command line as a single word. This word contains every parameter that appears in the command line. Basically the $* variable treats these parameters as a whole, not as multiple individuals. The [email protected] variable treats all arguments supplied on the command line as multiple independent words in the same string. This allows you to iterate through all the parameter values and get each parameter. This is usually done through the for command.   Move variable: When you use the shift command, it moves each parameter variable one position to the left by default. Therefore, the value of the variable $ $ is moved to the $ $, the value of the variable is moved to $ $, and the value of the variable is deleted (note that the value of the variable, the program name, does not change). You can move multiple locations in one place, and you just need the shift command to provide a parameter that indicates the number of positions you want to move. Be careful when using the shift command. If a parameter is moved out, its value is discarded and can no longer be recovered.  shell will use a double broken line to indicate the end of the list. After the double break, the script can safely treat the remaining command-line arguments as arguments, rather than as options.   Using the getopts command: The getopts command is as follows: getopts optstring variable valid option letters are listed in optstring, and if the option requires a parameter value, add a colon. To get rid of the wrong information, you can add a colon before the optstring. The getopts command saves the current parameter in the variable defined in the command line. $ cat test19.sh#!/bin/bash# Simple demonstration of the getopts command#echowhile getopts:ab:c optdocase "$opt" INA) echo "Found the-a option";; b) echo "Found the-b option, with value $OPTARG";; c) echo "Found the-c option";; *) echo "Unknown option: $opt ";; Esac done$$./test19.sh-ab test1-cfound the-a option Found the-b option, with value test1 Found the-c option$

 

  Get user input Basic read: The read command accepts input from a standard input (keyboard) or another file descriptor. The echo command that generates the hint uses the-n option. This option does not output line breaks at the end of the string, allowing the script user to follow the input data followed by the next line. In fact, the Read command is wrapped with-p, allowing you to specify the prompt directly on the read command line.   Timeout: the-t option specifies the number of seconds that the read command waits for input. When the timer expires, the Read command returns a non-0 exit state code.  #!/bin/bash# timing The data entry if read-t 5-p "Please enter your name:" Namethenecho "Hello $name, welcom E to my script "Elseechoecho" Sorry,too slow! " fi$./test25.shplease enter your Name:sorry, too slow!$  can not timing the input process, but instead let the read command count the number of characters entered. When the entered character reaches the preset number of characters, it exits automatically and assigns the input data to the variable. $#!/bin/bash# getting just one character of Input#read-n1-p "Do you want to continue [y/n]?" Answercase $answer Iny | Y) Echoecho "Fine, continue on ...";; N | N) Echoecho OK, Goodbyeexit; Esacecho "This is the end of the script" $./test26.shdo-Want to continue [y/n]? Yfine, continue on ... This is the end of the script$  hidden way read sometimes you need to get input from the scripting user, but again the input information is displayed on the screen. The typical example is the input password, but there are many other types of data that need to be hidden. The-s option prevents data entered in the Read command from appearing on the monitor (in fact, the data is displayed, except that the read command sets the text color to be the same as the background color). #!/bin/bash# hiding input data from thE monitor#read-s-P "Ener Your password:" Passechoecho "is your password really $pass?" $./test27.shener your password:is your password really df?$  read from file: $ cat test28.sh#!/bin/bash# reading data from a F Ile #count =1cat Test | While read line Doecho "line $count: $line" count=$[$count + 1] doneecho "Finished processing the file" $$ cat testthe Quic K Brown dog jumps over the lazy fox. This is a test, which is only a test. O Romeo, romeo! Wherefore art Thou romeo?$$/test28.shline 1:the quick brown dog jumps over the lazy fox. Line 2:this is a test, which is only a test. Line 3:o Romeo, romeo! Wherefore art thou Romeo? Finished processing the file $  standard descriptor:

 

For the terminal interface, the standard input is the keyboard. The standard output is the terminal display. $ ls-al Test test2 test3 badtest 2> test6 1> test7 $ cat Test6 ls:cannot access test:no such file or directory ls : Cannot access badtest:no such file or directory $ cat test7-rw-rw-r--1 Rich 158 2014-10-16 11:32 test2-rw-rw-r-- 1 Rich rich 0 2014-10-16 11:33 test3 $shell The normal output of the LS command is redirected to the Test7 file using the 1> symbol, and the error message is redirected to the 2> file via TEST6 compliance. Redirect to the same output file using the redirect symbol &>.   Temporary redirection: If you have an error message in your script, you can redirect a separate line of output to stderr. All you need to do is redirect the output information to the stderr file descriptor using the output redirection character. When redirecting to a file descriptor, you must precede the file descriptor number with a &:echo "This was an error message" >&2  Permanent redirection: Use the EXEC command to tell the shell to redirect a specific file descriptor during the script execution period. $ cat Test10 #!/bin/bash # Redirecting all output to a file exec 1>testoutecho "This is a test of redirecting all OUTPU T "echo" from a script to another file. "echo" without have to redirect every individual line "$./test10 $ cat Testout This was a test of redirecting all output from a script to another file. Without has to redirect every individual line $  

Bash Shell Learning notes (i)-Common commands

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.