Shell -- getting started with shell

1. Introduction to shell

1. Configuration requirements:

OS: RHEL7 or CentOS8 is recommended

CentOS8 will stop maintenance at the end of 2021

RHEL8 or dragon lizard operating system https://openanolis.cn

2. Classification of Shell Scripting Language

There are two kinds of shells: Bourne shell and C shell

Bourne shell includes Bourne shell (SH), Korn shell (KSH) and Bourne again shell (bash).

C shell includes csh and tcsh.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-r7qrcwx2-164689898757) (C: \ users \ yayaya \ appdata \ roaming \ typora user images \ image-20220309233951775. PNG)]

You can view the Shell support of CentOS 6 system through the following commands

# View the Shell support of CentOS 6 system
[root@servera study]# cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash

# View the system default shell
[root@servera study]# echo $SHELL
/bin/bash
[root@servera study]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash

Example 1.1:

Write a statement including commands, variables and process control to clear / study / test txt

[root@servera study]# cat rmlogs.sh 
# !/bin/bash
logDir=/study

#If not root
if [ "$UID" -ne 0 ]
then
	echo "Must be root to run this script!"
	exit 1
fi
# If the directory switching is not successful
cd $logDir || {
	echo "Cannot change to neccessary directory."
	exit 1
}
>/study/test.txt && {
	echo "Logs cleaned up"
	exit 0
}
echo "Logs cleaned up failed."
exit 1

2. Establishment of shell script

1. Start of script (first line)

The first line of a normal shell script will indicate which interpreter is used to execute the contents of the script

#!/bin/bash
 or
#!/bin/sh

2. Difference between Bash and sh

bash is slightly different from sh. it also includes the features of csh and ksh, but most scripts can run on SH without modification, such as:

[root@servera study]# ll /bin/sh
lrwxrwxrwx. 1 root root 4 Jul 27  2021 /bin/sh -> bash
[root@servera study]# ll /bin/bash
-rwxr-xr-x. 1 root root 1150584 Jul 27  2021 /bin/bash

⏰ SH is the soft link of bash. In most cases, there is no difference between "#! / bin/bash" and "#! / bin/sh" at the beginning of the script, but the more standardized way is to use "#! / bin/bash" at the beginning of the script.

3. Execution of shell script

When the Shell script runs, it will first look for the system environment variable ENV, which specifies the environment files (loading order: / etc/profile, /. bash_profile /, /. Bashrc, / etx/bashrc, etc.)

shell scripts can be executed in the following ways:

(1) Bash script name or sh script name (recommended)

(2) Path / script name or/ Script name (requires script execution permission: Chmod + X script name)

(3) Source script name or script-name

(4) SH < script name or cat script name|sh

4.shell writing specification

1. The first line of the shell specifies the script interpreter

2. Try not to use Chinese for notes, not limited to notes

3. If you need to display the version, author, copyright and other information at the beginning of the shell script, you can edit the settings in "~ /. vimrc"

[root@ scripts]# cat ~/.vimrc
autocmd BufNewFile *.py,*.cc,*.sh,*.java exec ":call SetTitle()"
func SetTitle()
    if expand("%:e") == 'sh'
        call setline(1,"#!/bin/bash")
        call setline(2,"##############################################################")
        call setline(3, "# File Name: ".expand("%"))
        call setline(4, "# Version: V1.0")
        call setline(5, "# Author: kongd")
        call setline(6, "# Email: kongd@163.com")
        call setline(7, "# Organization: http://www.cnblogs.com/kongd/")
        call setline(8, "# Created Time : ".strftime("%F %T"))
        call setline(9, "# Description:")
        call setline(10,
        "##############################################################")
        call setline(11, "")
    endif
endfunc

4. The script name should be sh is the extension

5. The shell script should be stored in a fixed path

5.shell features

Basic functions of bash

1. Historical orders

1) View of historical commands

[root@localhost ~]# History [options] [save file with history command]

Options:
-c: Clear history command
-w: Write the history command in the cache to the history command save file. If you do not manually specify the historical command to save the file, put the default historical command to save the file ~ / bash_ In history

[root@localhost ~]# vi /etc/profile
... H
ISTSIZE=1000

2) Call of historical command

Method of executing historical command

Use the up and down arrows to invoke previous historical commands
 Use“!n"Repeat the second step n Historical commands
 Use“!!"Repeat the previous command
 Use“!String "repeats the last command that begins with this string
 Use“!$"Repeat the last argument of the previous command

2. Completion of orders and documents

Bash command completion enhancement package bash completion, which supports the completion of systemctl command service name

3. Command alias

[root@localhost ~]# Alias alias = 'original command'

Aliases have a higher priority than commands. What is the specific order in which commands are executed? What is the order of command execution?

1, The first sequence executes a command executed with an absolute path or a relative path.
2, The second sequence executes the alias.
3, Third order execution Bash Internal commands.
4 The fourth sequence shall be implemented according to $PATH The first command found in the directory lookup order defined by the environment variable.
To make this alias permanent, you can write the alias to the environment variable configuration file“~/.bashrc". 

4.Bash common shortcut keys

ctrl+A Move the cursor to the beginning of the command line
ctrl+E Move the cursor to the end of the command line
ctrl+C Force termination of the current command
ctrl+L Clear screen, equivalent to clear command
ctrl+U Commands before deleting or cutting the cursor
ctrl+K Delete or cut the content after the cursor
ctrl+Y paste ctrl+U or ctrl+K Cut content
ctrl+R Search in history commands
ctrl+D Exit the current terminal
ctrl+Z Pause and put in the background
ctrl+S Pause screen output
ctrl+Q Restore screen output

5. I / O redirection

1) Bash standard I / O

Device file name file descriptor type
 Keyboard /dev/stdin 0 Standard input
 monitor /dev/stdout 1 standard output 
monitor /dev/stderr 2 Standard error output

2) Input redirection
< 3
)Output redirection

TypeSymboleffect
Standard output redirectionCommands > fileOutput the correct output of the command to the specified file or device by overwriting.
Command > > fileOutput the correct output of the command to the specified file or device in the form of addition.
Standard error output redirectionError command 2 > fileOutput the error output of the command to the specified file or device by overwriting.
Error command 2 > > fileOutput the error output of the command to the specified file or device in the form of append.
Correct output and error output are saved at the same timeCommands > file 2 > & 1The correct output and the wrong output are saved in the same file by overwriting.
Command > > file 2 > & 1The correct output and error output are saved in the same file by appending.
Command & > fileThe correct output and the wrong output are saved in the same file by overwriting.
Command & > > fileThe correct output and error output are saved in the same file by appending.
Command > > file 1 2 > > file 2Append the correct output to file 1 and the wrong output to file 2

6. Wildcard common syntax

1,*: Match any character of any length, that is, "anything is OK".
/etc/fs* #/Files starting with fs in etc will be matched
/tmp/my*1 #/Files that start with my and end with 1 in tmp will be matched
2,?: Matches any single character.
myfile? #Any file named myfile followed by any single character will be matched
/tmp/notes?txt #If / TMP / notes Txt and / TMP / Notes_ If TXT exists, they will be matched
3,[ ]: And?Similarly, you can match a character in parentheses, or you can use“-"Specify the scope.
myfile[12] #Will match myfile1 and myfile2
[Cc]hange[Ll]og #Changelog, changelog, changelog and changelog can all be matched, which is the same as that in uppercase
 It is useful to use bracket wildcards when matching deformations
ls /etc/[0-9] #Lists all files that start with a number in / etc.
ls /tmp/[A-Za-z] #All files in / tmp that begin with uppercase or lowercase letters are listed.
4,[!]: "!" in parentheses It means not to match the characters in parentheses.
rm myfile[!9] #Delete all files named myfile plus one character except myfile9
5,{}Generating sequence
touch file{1..9}.txt #The current path generates file1 txt~file9. txt.  {a..f} stands for a-f, discontinuous use, points
 Septum, for example f{1,3,5}.txt
6,use{}backups
cp file1.txt{,.bak} #Put fiel1 Txt copy a file called file1 txt. bak
cp file{2,22}.txt #Copy File2 Txt is file22 txt

Examples

1,list/etc/The table of contents is not written in letters a reach n Begin with and begin with.conf Ending file
ls /etc/[!a-n]*.conf

2,list/etc/List with letters a reach n Begin with and begin with.conf Ending file
ls /etc/[a-n]*.conf

3,list/bin/Below c or k File name starting with
ls /bin/[ck]*

Keywords: Linux CentOS shell bash

Added by mcog_esteban on Thu, 10 Mar 2022 10:18:30 +0200