[Chapter I.] Shell Basics

Source: Internet
Author: User
Tags aliases control characters stdin syslog

What is a Shell?Outline "Preface "
1. Shell Introduction
2, Bash function introduction
2.1. Record command history
2.2. Command and file name completion
2.3. Aliases
2.4. pipe character/redirect 2.5. Shortcut keys
3. Bash Usage Tips
3.1. Redirection skills
3.2, command serial number use skill
3.3, operation control Skills 3.4. tips for using curly braces {}
  Preface:Shell Scripting is an essential part of your daily Linux system administration. If you don't write a shell script, you're not a qualified administrator. At present, many units in the recruitment of Linux system administrators, Shell script writing is a must-test project, in short, as long as the shell script is good, the Linux job search the road is much easier.
1. Shell Introduction
    • The shell is the intermediate medium used when the system interacts with the computer hardware, and it is just a tool of the system. In fact, a complete computer architecture includes: hardware and software, and software is divided into system software and application software, is responsible for the hardware management and operation is the kernel part of the system software, the user is not directly with the hardware or the kernel to deal with, The user sends instructions through the program or part of the system software (perhaps sending a message via a browser), which is translated and passed to the kernel, and the kernel dispatches the hardware resources to complete the operation (for example, sending a packet using a network card) after knowing the user's needs.
    • In a Linux environment, we can communicate with the kernel through the shell, and ultimately we want to use the computer resources. However, the open features of Linux, so that there are many options for the shell under Linux, CentOS 6.4 system can be used in the shell has/bin/sh,/bin/bash,/bin/tcsh,/bin/csh these kinds,/etc/ The shells file describes which shells are available for the current system. Of course, different sehll have different characteristics and modes of operation. CentOS defaults to bash.
2, Bash function introduction 2.1. Record command History Bash has the ability to automatically record command history, and commands executed by the user are automatically logged to the. bash_history[1] Hidden file in their home directory when logging off. There are many ways to view these history, and you can open the file directly to view it. Use the keyboard's top and bottom buttons to flip or flip through history, and you can also view history with the historical command. All command histories have a record number. The amount of information that the command history can record is determined by the histsize variable, and Centos 6.4 defaults to the/etc/profile file that defines histsize=1000, where 1000 is the maximum number of 1000 commands that are used recently. If the first command is overwritten when there are 1001 commands, execute the command history-c command to clear all history commands Record command History in addition to viewing the history, you can also call the history directly when needed to execute the command again.
    • Up and down the key to scroll through the history command, find the appropriate command after the direct return to execute.
    • Input! XXX call command history (XXX for keywords), such as! LS will invoke the last command executed with LS
[Email protected] ~]#!lslsanaconda-ks.cfg  install.log  install.log.syslog
    • The above is the call keyword, you can also use!n to accurately locate the history, such as!65
[Email protected] ~]#!65ls-ltotal 20-RW-------. 1 root root 1101 Jul 07:03 anaconda-ks.cfg-rw-r--r--. 1 root root 8838 Jul 07:03 install.log-rw-r--r--. 1 root root 3091 Jul 07:02 install.log.syslog
    • There is also a function, through the Ctrl+r shortcut key to open the search function, and then enter the keyword, you can search the command history of the relevant commands, press ENTER to complete the operation. If you don't find the right command, press ESC to launch the search.
2.2. Alias and file name completion
    • Pressing the TAB key helps us to complete an instruction, a path, or a file name. Press the TAB key two times and the system will list all the commands or filenames.
2.3. Aliases
    • In the Centos6.4 system, you can use the LL command to display the details of the file, but there is no ll command in the system, it is just a pre-defined alias. The advantage of aliases is that you can simplify abbreviations for very long instructions, and creating aliases for common and complex commands and options can greatly improve your daily productivity.
[[email protected] ~]# alias            <== View all current aliases of the system alias cp= ' cp-i '                    <==CP Copy command The fact is Cp-ialias l.= ' ls-d. *--color=au To ' Alias ll= ' Ls-l--color=auto ' Alias ls= ' ls--color=auto ' alias mv= ' mv-i ' Alias rm= ' rm-i ' Alias Which= ' Alias | /usr/bin/which--tty-only--read-alias--show-dot--show-tilde '     [[email protected] ~]# alias h5= ' head-5 '         <= = Define a new alias [[email protected] ~]# unalias h5                  <== de-Define Alias
2.4. Pipe character/redirect
    • Pipe symbol: "|" He takes the output of the previous instruction as input to the latter instruction
[Email protected] ~]# echo "Xiaoling" | passwd--stdin vforbox              <== set vforbox password to xiaolingchanging password for user vforbox.passwd:all authentication Tokens updated successfully. [Email protected] ~]# Rpm-qa | grep gcc              <== queries whether the GCC software is installed on the computer libgcc-4.4.7-11.el6.i686gcc-4.4.7-11.el6.i686
    • Redirect: Output redirection can use the > or >> symbol, use > to import the output to a file, create the file if it does not exist, overwrite the file if it already exists, and use >> to append the output to the file The redirection of the corresponding error message requires the use of 2> or 2>>. Input redirection can use the < symbol, which can help us extract input information from a file.
[[email protected] ~]# ls <== view current file list anaconda-ks.cfg Install.log install.log.s Yslog list.txt[[email protected] ~]# ls > list.txt <== to keep output to list.txt, no output display on the screen [[Email protecte D] ~]# hostname >> list.txt <== Append the hostname to the end of the List.txt file [[email protected] ~]# mail-s test [EMAIL&NB              Sp;protected] < List.txt <== send mail, message content from file [[email protected] ~]# ls-l ABC Install.log <== view file details, ABC does not exist Ls:cannot access abc:no such file or Directory-rw-r--r--. 1 root root 8838 Jul 07:03 install.log[[email protected] ~]# ls-l ABC install.log 2> error.txt &l t;== only redirects the error without affecting the normal output-rw-r--r--.              1 root root 8838 Jul 07:03 install.log[[email protected] ~]# ls-l ABC install. Log > All.txt 2>&1               <== the correct output and error output are both imported all.txt[[email protected] ~]# ls ABC install.log >> all.txt 2>&1 <== append both the correct output and the error output to the All.txt
2.5. Shortcut keys
    • Bash provides a number of shortcut keys for the user to use, mastering these shortcuts can improve productivity
Shortcut keys Function description Shortcut keys Function description
CTRL + A Cursor moves to the beginning of the line Ctrl+k Delete the character of the cursor to the end of the line
Ctrl+e Move cursor to end of line CTRL + C Terminating a process
Ctrl+f Move the cursor one character to the right CTRL + Z Suspend process (Jobs command view pending process)
Ctrl+b Move the cursor left one character Ctrl+w Delete Cursor one word of money
Ctrl+l Clear the screen, equivalent to the clear command Alt+d Delete a word after the cursor
Ctrl+u Remove the character from the beginning of the cursor Tab Auto-complete
3. Bash Usage Tips
    • 3.1. Redirection skills
    • Write a script to automatically modify the password of the system account, then the default current password modification after the system will appear successfully prompt message, if you need to modify 20 user account password, such as cases, a lot of success information is not the focus of our attention, Administrators are more concerned about error hints . So at this point you can consider the standard correct output shielding, Linux provides a special device/dev/null, it is to the sun black hole, anything to the inside of the write will disappear forever. For large amounts of meaningless output information, the/dev/null device can be imported by redirection
[[email protected] ~]# echo "admin" | passwd--stdin root >/dev/null     <== set root password for admin output import to/dev/null, no screen display
    • The standard output is decoupled from the error output redirection, and many times when the autorun script is completed unattended when the server is running at the lowest load of the night, then when the administrator checks the script to see which commands are executed successfully, which have problems, and for ease of administration, Separate redirection is especially important if you need to keep the correct output and error output in two separate record files.
[[email protected] ~]# ID vforbox >> user 2>> error        <== Check if the system exists Vforbox user, if present will log information to the user file, Otherwise log error
3.2. Command sequence usage tips
    • In Linux, we can use control characters [;, &&, | |, &]
[[email protected] ~]# sleep &              <== background Run command, does not affect the use of the current shell [ro[email protected] ~]# ls/tmp; ls/root; Ls/hom E              <== All commands are executed sequentially (regardless of whether the previous command is successful, the following commands must be executed) [[email protected] ~]# ls all.txt && cat all.txt              <== If a file exists, the contents of the file are displayed, otherwise an error (the CA is executed only if LS execution succeeds) [[email protected] ~]# Gedit | | Vim              <== If you have a gedit editor, open the program, otherwise open the Vim editor [[email protected] ~]# ID vforbox &>/dev/null && echo "Hi, Tom "| | echo "No such user"              
3.3, Operation control skills
    • When running a process, you can make it pause (press CTRL + Z), then use the FG command to restore it, or use the BG command to make it run in the background, or you can make it stop, (press CTRL + C)
[[email protected] ~]# sleep &              <== in the background with "&" sign [1] 4694[[email protected] ~]# jobs              <== You can see tasks that are paused or are running in the background [1]+  Running                 sleep &[[email protected] ~]# sleep              200 seconds and then use CTRL + Z to pause <== [2]+  Stopped                 sleep 200[[email protected] ~]# jobs              <== can see tasks being paused or being run in the background [1]-  Running                 sleep 100 &[2]+  Stopped                 sleep 200[[email protected] ~]# FG 1              <== recovery number 1 back to reception
    • What if I turn off the running tasks in the background?
    • 1) If you do not exit the current shell, you should first use the command "fg+ number" to move the task to the foreground, and then press CTRL + C to end
[[email protected] ~]# FG 1              <== recovery number 1 back to reception Vmstat 1 >/tmp/1.log^c
    • 2) Another case is that when you close the current shell and open another shell again, using the jobs command does not show the background or suspended tasks, and if you want to close those tasks, you must know their PID
[[email protected] ~]# Vmstat 1 >/tmp/1.log &              <== use "&" to put the task in the background run will show pid[1] 1184[[email protected] ~]# p S aux |grep vmstat              <== View Vmstat process pidroot 1184 0.0 0.1 560 pts/0    s    00:15   0:00 vmstat 1root      1186  0.0  0.1   4356   728 pts/0    s+   00:15   0:00 grep Vmstat[[email protected] ~]# kill 1184                            <== kill Vmstat Process
    • If you encounter a process that is not finished with Kill, you can add an option "-9", which is the kill-9 PID  
3.4. Tips for using curly braces {}
    • Extensions of parentheses can be used to survive a string of strings required by the command line or script, and parentheses can contain sequential serial numbers or multiple items separated by commas, successive sequences include a starting point and an end point, and use ... Segmentation
[[email protected] ~]# echo {a,b,c,d,e} <== output a b c d EA b c D e[[email protected] ~]# echo user{2,5,8,10} <== output user2 user5 user8 user10user2 user5 user8 User10[[email protec Ted] ~]# echo {0..5} <== output 0 1 2 3 4 1 2 3 4 5[[email protected] ~]# echo {0 ..                                10..2} <== Output even 0 2 4 6 8 2 4 6 8 10[[email protected] ~]# Echo x{2..-1}                 <== output x2 x1 x0 x-1x2 x1 x0 x-1[[email protected] ~]# touch/tmp/{a1,a2,a3} <== create A1 A2 A3 and other files [[email protected] ~]# ls-l/tmp/a{1,2,3} <== view A1 A2 A3 Properties-rw-r--r- -. 1 root root 0 Jul 02:41/tmp/a1-rw-r--r--. 1 root root 0 Jul 02:41/tmp/a2-rw-r--r--. 1 root root 0 Jul 02:41/tmp/a3[[email protected] ~]# chmod 777/tmp/a{1,2} <== give A1 a2 full privileges [[E     Mail protected] ~]# ls-l/tmp/a{1,2,3}                       <== View A1 A2 A3 familiar with-rwxrwxrwx. 1 root root 0 Jul 02:41/tmp/a1-rwxrwxrwx. 1 root root 0 Jul 02:41/tmp/a2-rw-r--r--.  1 root root 0 Jul 02:41/tmp/a3

[Chapter I.] Shell Basics

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.