Bash Shell Cognition

Source: Internet
Author: User
Tags control characters printable characters

Shell principle Cognition:

About wildcard characters in the shell *

The shell expands the wildcard character before passing it to the command, such as "ls-ld/usr/include/*" first expands to "Ls-ld file-list,"


View history:

You can view the command history with the historical command.

can be used one!! Executes the previous command


Bash Startup:

Find the global Settings/etc/profile, then look for the settings under the user's home directory,. Bash_profile.bash_login. Profile. By priority, the previous file is executed and will not be executed later.


Command-line prompt:

The command-line prompt is defined by the built-in variables PS1 and PS2, PS1 is the main prompt, PS2 is the same command that appears after wrapping, called from the prompt or the vice-prompt, more details can be viewed Manbash prompting segment. Variables can be modified by the Export command


Redirect:

Using the > symbol redirection will overwrite the original file and open the Bash option Noclobber will not

Open Noclobber:set-o Noclobber

Close Noclobber:set+o Noclobber

> if not specified, standard output 1> is used by default

Specify the standard output and error output as the same:command> outputfile 2>&1

The tee command can be both output and saved to a file in standard output

The block statement redirects the output of multiple statements together with redirection you can use {} ({Command;command;command;} >output.file) to enclose the statement and then use the redirect

Another way is to put a sequence of commands on a child shell to execute, enclosed in () (Command;command;) >output.file


Use redirection for statement blocks in scripts: Some important code, note:

Whileread Line

Do

count=$ ((count+1))

echo$ (count): $ (line)

done< $file > $filename. Lined


Pipeline:

Let the command accept parameters receive data from the pipeline: Rm-i $ (Find-name ' *.out ')


Heredocument:

command<< delimiter

......

>delimiter



File Descriptor:

Shell command line Each command automatically opens 3 descriptors stdin0,stdout 1, STDERR 2

A script needs to output different data to different files:

echo "Data to file descriptor 3" >&3

echo "Data to file descriptor 4" >&4

echo "Data to file descriptor 5" >&5





Run the command./shname3>outputfile3 4>outputfile 5>outputfile


One script multiple command inputs or outputs use the same file, but the file name is long:

EXEC 4>outfile.nameexec 5>&4echo "data to file Descriptor" 1>&5echo "data to file descriptor" >&4e Xec 4>&-exec 5>&-








Open Descriptor:

Execfd>outputfile if the file already exists, overwrite the

Execfd>>outputfile in Append mode

Open and ready to use: Command 1>&FD


The input descriptor is similar in the case

Execfd<inputfile

Execfd2<&fd1

COMMAND<&FD2 = Command <&fd1

Use <> to read/write files at the same time

Use execfd&-to close a descriptor


Process:

List the processes:

Ps-ef View all processes of the system, E to view all processes, equivalent to-A. F displays each process in full format (Uidpid C-Occupied CPU time percentage stime-start time TTY time consumes CPU cmd-start command)

Shows the program associated with the specified TTY

-T

Specify the list of concerns for the PID

Multiple PID can be connected after-p

Show a user's process

-U

Show processes created by a process

-C

List process Directories

The same branch is enclosed in [] and preceded by a number. The child threads are represented by the process name and placed in {}, preceded by a number. -c option to make branching non-consolidated


Command behind add & Execute in background

Jobs Displays information: Running is running, stoping means suspended, plus represents the FG default Action object, number indicates task number, FG usage: fg% task number. BG command to put suspended tasks in the background to continue running

The task in the background ends when bash ends, and you can use the Nohup command to prevent this, and when bash finishes, the task's parent process will be 1. Nohupmake &


Kill Process:

Kill multiple processes at once Killall


/proc/File System:

The virtual file system exists only in memory, and the directory in the/proc/directory represents a process (the number is PID) that holds the information for all processes, and the directory structure of all processes is the same.

Some directories in the process directory

CmdLine

The file contains the entire command line that started the process. It is not formatted, and there are no spaces between the program and its parameters, and the trailing line is not wrapped.

Cwd

The symbolic link points to the current working directory

Environ

The file contains all the environment variables defined for this process, in the format "variable = value", not formatted

Exe

The symbolic link points to the executable file that the process executes

Fd

This directory contains all the descriptors currently open by the process (a list of file symbols, each open file symbol represented by a symbolic link whose name is the number of the file descriptor and the file that the file descriptor opens)

Maps

When you print the contents of the file, you see that part of the process's address space that is currently mapped to the file in the address space that is associated with the map, the permissions associated with the map, the offset from the start of the map (from the beginning of the file), the primary, ordinal (HEX) of the mapped file device, The inode ordinal of the file, and the file name

Root

The symbolic link points to the root directory used by the process

Status

This file contains a number of information, including the executable file name, current state, PID, PPID, actual and valid UID and GID, memory usage


Various hardware information on the machine:

Cpuinfo

This file contains information about the CPU on the user's machine

Modules

This file contains the list of modules currently used by the kernel, and the number of times each module is used (information reported by Lsmod)

Meminfo

The file contains information about memory usage (the free command is just an easy-to-read format display)

Devices

Available devices, including character devices and block devices

Filesystems

System-Supported file systems

Ioports

View the I/O port of the system

Interrupts

View interrupt Information

Mounts

To view mounted file systems

Swaps

To view the usage of the swap partition

Partitions

To view information about the system partition

Version

View Kernel version


Kernel source Documention/filesystems/proc.txt includes a complete /proc/ File system Introduction, and explained the /proc/ format and meaning of all files in the file system


/proc/sys/is a special subdirectory of/proc that allows you to display the parameters that are running on the current kernel, and can change these parameters in the system run, and it will take effect immediately.

Example: Sudoecho 1 >/proc/sys/net/ipv4/ip_forward

This is only valid when the system is running, and when the system restarts , it changes back to the default value, so you can change the values when you want to start by modifying the configuration file /etc/sysctl.conf , you can refer to mansysctl.conf (5)


Text manipulation and string handling:

Remove the most recently accessed 5 ordinary files from a directory and output the file name and last access time:

Ls-lut |grep "^-" |head-5 |cut-c 41-

Connect the rows of the two text files (just join them)

Paste-d ': ' File1 file2

Three text to connect together:

Paste-d ' < ' file1 file2 |paste-d ' > '-file3


Check the various shells in the current system and count how many users are using them and print them out in more than one order:

cat/etc/passwd|cut-d:-f7 |SORT|UNIQ-C|SORT-NR


Count the number of occurrences of each word in a text file

#!/bin/bash

Count () {

if[$#! = 1]

Then

echo "need one file parameter to work!"

Exit1;

Fi


# Remove punctuation and special characters

# Build a Long pipeline command, write a single line for each paragraph to increase readability

TR ' +-=*.,;:{} () #!? <> "\n\t" <$1 |\

# Convert all uppercase letters to lowercase letters

Tr ' A-Z ' A-Z ' |\

# Convert a continuous space character to a space character

Tr-s ' |\

# convert whitespace to line break

Tr ' \ n ' |\

# Put the same words together

Sort|\

# Delete duplicate words and make statistics

Uniq-c |\

# Sort According to the number of repetitions

Sort-rn

}


Echo

echo "This script can count words of a specified file."


# Build an infinite loop with a null command colon

While

Do

Read-p "Enter the file path (or quit):"

Case ' $REPLY ' in

[qq]| [Qq] [Uu] [Ii] [Tt])

echo "Bye."

Exit0

;;

*)

if[-F "$REPLY"] &&[-R "$REPLY"]&&[-s "$REPLY"]

Then

Count "$REPLY"

Else

echo "$REPLY can not is dealed with."

Fi

;;

Esac

Done


Exit0



The TR command provides a character set for ease of use:

Alnum

All letters and numbers

Alpha

All letters

Blank

All levels of whitespace

Cntrl

Control characters

Digit

Digital

Graph

printable characters, but not spaces

Print

printable characters, including spaces

Lower

lowercase English letters

Upper

Uppercase English letters

Punct

All punctuation

Space

All horizontal and vertical whitespace

Xdigit

hexadecimal digits

Syntax: tr[option] ... ' [: ClassName:] ' SET2 '



Replace tab with a space of the same width:

Use the expand command. Unexpand the opposite, but the default only converts the Header tab using UNEXPAND-A for all conversions


Format the output as a table:

(printf "PERMISSIONS LINKS OWNER GROUP SIZE DATE hh:mm file-name\n"; ls-l |sed 1d) |column-t



Debug

Bash-n does not really perform, only check the syntax, do not do the substitution and other operations

The-v option allows the shell to output every line of code that has been processed in the script

The-X option allows bash to run under Trace, outputting each executed statement and replacing it.


Partial commissioning:

Add Set-option to the script

option can be any of-N,-V,-X.

Close with Set+option



Using the Trap command

3 Pseudo-signals:

When exit exits from a function and the entire script finishes executing

Err when a command execution fails to return a non-0 state

Before each command in the debug script executes


The ERR signal can be captured to track unsuccessful commands, $LINENO is the shell's built-in variable, which represents the current line number of the shell script.

An interesting command or usage:
    1. Cal: Print a calendar

    2. The output of the LS command is redirected after a line of files, equivalent to ls-1 this is the LS command internal judgment, you can use the Ls-c force-like output

    3. The expr command computes an arithmetic expression and a relational expression and can also be used to calculate the length of a string, such as: Exprlength string

    4. The basename command removes the path from the file name, basename./ETC/INIT.D output is Init.d basename./etc/init.d. D output is init. Removed the suffix.

    5. Cat command-e option to see the location of individual line breaks in footstep files


This article is from the "No Front" blog, please be sure to keep this source http://qianyang.blog.51cto.com/7130735/1615564

Bash Shell Cognition

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.