Linux Shell Basics

Source: Internet
Author: User
Tags aliases bitwise clear screen

View the default shell types supported in Linux:


Echo Output command

-e support for character conversions with backslash control

Control character (requires quotation marks)
\\ Output \ Itself
\a Output warning tone
\b Backspace key, delete left
\c Cancels the line break of the last line of the output, and the-n consistent
\e Escape key
\f Page break
\ n Line break
\ r Enter
\ t tab, TAB key
\v Vertical tab
/ Output characters by octal ASCII, where 0 is a number
\x Output characters by hexadecimal ASCII code

such as: Echo-e "a\tb\tc\nd\ne\nf\n"

Echo-e "\e[1;31m abcdefgh\e[0m" Output color

#30m = black; 31m= red; 32m= Green; 33m= Yellow

#34m = blue; 35m= pink; 36m= cyan; 37m= White

How the script executes:
    1. Relative path or absolute path execution (requires EXECUTE permission):./
    2. Call via Bash (Read permission only): Bash

Shell scripts written under Windows cannot be executed on Linux:

is because the carriage return under Windwos is ^m$, and the return character of Linux is $

Rpm-q Dos2unix #查看是否安装dos2unix

Yum Install-y Dos2unix

Dos2unix filename


History View Historical Commands

-C Empty History command

-W writes the history command in the cache to the history command to save the file ~/.bash_history

Alias query command aliases

Alias aliases = "Original Command"

Unalias Deleting aliases

/ROOT/.BASHRC the alias to take effect permanently

Command execution order
    • Perform commands executed with absolute or relative paths
    • Perform aliases
    • Execute bash Internal commands
    • Executes the first command found in the order of directory lookups defined by the $PATH environment variable

Bash common shortcut keys
CTRL + A Move the cursor to the beginning of the command line
crol+ E Move the cursor to the end of the command line
CTRL + C Force change force to terminate the current command
CTRL + L Clear screen, equivalent to clear
Ctrl-u Delete or cut the content before the cursor
CTRL + K Delete or cut the contents after the cursor
Ctrl + Y Paste Ctrl+u or ctrl+k-cut content
CTRL + R Search in the history command
CTRL + D Exit Current Terminal
CTRL + Z Pause and put into the background
CTRL + S Pause Screen Output
CTRL + Q Restore Screen Output

Output redirection
Standard output redirection Commands > Documents The correct output of the command to a specified file or device in a covered manner
Commands >> Documents Output the error of the command to the specified file or device in an additional way
Standard Error Output redirection Error command 2> file To export the error of the command to the specified file or device in a overwritten manner
Error command 2> file Output the error of the command to the specified file or device in an additional way
Correct output and error output are saved simultaneously Commands > Documents 2>&1 The correct output and error output are saved in the same file in a covered manner
Commands >> Documents 2>&1 Save the correct output and error output in the same file in an additional way
Commands &> Documents The correct output and error output are saved in the same file in a covered manner
Commands &>> Documents Save the correct output and error output in the same file in an additional way
Commands >> files 1 2>> file 2 Append the correct output to the file 1, append the wrong output to the file 2

Sequential execution of MULTIPLE commands
Command 1; command 2 Multiple command order execution, no logical connection between commands
&& Command 1&& Command 2 Logic and. Command 2 does not execute when command 1 is executed correctly
|| Command 1| | Command 2 Logical OR. Command 2 does not execute when command 1 executes an error

Example: Command && echo yes | | Echo No

Command 1 | Command 2 pipe character (the correct output of command 1 as the Action object for command 2)

Example: MORE/ETC/PASSWD | grep "Root"

Wildcard characters
Match an arbitrary character
* Match 0 or more arbitrary characters, or match any content
[  ] Match any one of the characters in the brackets
[ - ] Matches any one of the characters in the brackets-representing a range.
[ ^ ] Logical non, which means that the match is not a character within the brackets. Example: [^0-9] stands for matching a non-numeric character
Other special symbols in bash
‘’ In single quotes all special symbols such as $ and ' (anti-quote) have no special meaning
“” Special symbols do not have special meanings in double quotes, except $, ', \ \ \ \ r \ n, with the special meaning of the value of the calling variable, the reference command, and the escape character
$() and ' (anti-quote) function. The content is a system command that executes it in bash first
# In the shell script, #代表注释
$ Used to invoke the value of a variable, such as the value of the variable name that needs to be called, you need to use $name to get the value of the variable
\ Escape character, the special symbol after \ Loses special meaning, becomes ordinary character. such as \$ will output $, while inappropriate variable references

A variable is a unit of computer memory where the stored value can be changed. When a shell script needs to save some information, such as a file name or a number, store it in a variable. Each variable has a command, so it's easy to refer to it. Variables can be used to save useful information, so that the system learns about user settings, variables can also be saved by the user temporary information

Variable setting rules
    • Variable names can consist of letters, numbers, and underscores. But you cannot start with a number.
    • In bash, the default type of a variable is a string type, and if you want to perform a numeric operation, you must specify the variable type as numeric
    • The variable is connected by an equal sign, and cannot have spaces on the left or right side
    • If there are spaces for the value of the variable, use single or double quotation marks to include
    • In the value of a variable, you can use the \ Escape character
    • If you need to increase the value of the variable, then you can make the variable value overlay AH. However, the variable needs to contain the $ variable name in double quotation marks or the variable name with $
    • If you assign the result of the command to a variable as a variable value, you need to use the back quotation mark or the $ () containing command
    • environment variable name recommended capitalization, easy to distinguish

Variable classification
    • User-defined variables
    • Environment variables: The main preservation of this variable is the data related to the operating environment of the system
    • Positional parameter variables: This variable is mainly used to pass parameters or data to the script, the variable name can not be customized, the role of the variable is fixed
    • Predefined variable: is a variable already defined in bash. Variable names cannot be customized, and the role of variables is fixed.

Local variable Overlay

abc= "Blog" #定义变量

Abc= "$ABC" int6


[Email protected] ~]# echo $abc #变量调用


Set #变量查看

Unset ABC #变量删除

Environment variables: User-defined variables take effect only in the current shell, while environment variables take effect in the current shell and all child shells of the shell. If the environment variable is written to the appropriate configuration file, the environment variable will take effect in all shells.

Setting environment variables

Export variable name = variable Value #申明环境变量

Env #查询变量

unset variable name #删除变量

System common Environment variables

Path: Paths to System lookup commands

Path= "$PATH":/home/test/

PS1: Defining a variable at the system prompt

\d: Show date, Format day and month

\h: Display host name

\ t: Show 24-hour system time

\ t: Show 12-hour system time

\a: Display 24-hour time, format hh:mm

\u: Displays the current user name

\w: Displays the full path of the current directory

\w: Displays the last directory in the current directory

\#: The first few commands to execute

\$: Prompt. Root user is #, normal user is $

Positional parameter variables
$n N is a number, and $ A represents the command itself, $1-$9 represents the first to the Nineth parameter, and more than 10 of the parameters need to be enclosed in curly braces, such as $[10]
$* This variable represents all the arguments in the command line, $* all the parameters as a whole
[Email protected] This variable also represents all parameters in the command line, but [email protected] treats each parameter differently
$# This variable represents the number of all arguments in the command line

Example: [[email protected] ~] #vim





sum=$ (($num 1+num2+num3))

Echo $sum

[Email protected] ~]#./ 1 2 3


Examples of differences between $* and [email protected]:

[[Email protected] ~] #vim


For x in "$*"


Echo $x


For y in "[email protected]"


Echo $y


[Email protected] ~]#./ 11 22 33 44

11 22 33 44





Pre-defined variables
$? The return status of the last command executed. If the value of this variable is 0, the previous command is executed correctly, and if the value of this variable is not 0 (which is determined by the command), the last command execution error is proved.
$$ Process number (PID) of the current process
$! Process number (PID) of the last process running in the background

Example: [[email protected] a] #ls-l

Total dosage 0

[[email protected] A] #echo $?


[[email protected] a] #error-l

Bash:error: Command not found

[[email protected] A] #echo $?


Example 2:[[email protected] ~] #vim


Echo ' Current process number is ' $$

echo ABCD &

Echo ' Current process number is ' $!

[Email protected] ~]#./

The current process number is 2917

The current process number is 2918


Read receive keyboard input

-P "prompt message" when waiting for the read input, the output prompt message

-T number of seconds the read command waits for user input, which specifies the wait time

-N Characters The read command accepts only the number of characters that are set. It will execute.

-s hides input data for confidential information input

Example: #!/bin/bash

Read-t 30-p "Please enter user name:" ID

echo "Input is $id"

Read-s-P "Please enter password" password

Echo-e "\ n"

Read-n 1-p "Please enter gender [male/female]" gender

Echo-e "\ n"

echo "Input is $gender"

[Email protected] ~]#./

Please enter user name: root

The input is root.

Please enter your password:

Please enter gender [male/female]: Male

The input is a male

Numeric operation and operator declare [+/-][option] Variable name

-: Set type attribute to variable

+: Cancels the Type property of a variable

-I: Declaring variables as integers (integer)

-X: Variable life as an environment variable

-P: Displays the declared type of the specified variable

Example 1:[[email protected] ~] #aa =11

[[Email protected] ~] #bb =22

[[Email protected] ~] #cc = $aa + $bb

[[Email protected] ~] #echo $CC


[[Email protected] ~] #declare-I cc= $aa + $bb

[[Email protected] ~] #echo $CC


Example 2:expr or let numeric operation

[[email protected] ~]# dd=$ (expr $aa + $bb)

[Email protected] ~]# echo $DD


Example 3:$ (expression) or $[-op)

[[email protected] ~]# ee=$ (($aa + $bb))

[Email protected] ~]# echo $ee


Priority level Operator Description
13 -,+ Monocular negative, Monocular positive
12 ! , ~ logical non, bitwise inverse or complement
11 *,/,% Multiply, divide, take the mold
10 +,- Add, Subtract
9 <<, >> Bitwise left SHIFT, bitwise right SHIFT
8 <=, >=, <, > Less than or equal to, greater than or equal to, less than, greater than
7 = =,! = Equal to, not equal to
6 & Bitwise-AND
5 ^ Bitwise XOR OR
4 | Press for OR
3 && Logic and
2 || Logical OR
1 =,+=,-=,*=,/=,%=,&=,

^=, |=,<<=,>>=

assigning, calculating, and assigning values

aa=$ ((14%3)) #14不能被3整除, the remainder is 2

aa=$ ((1&&0)) #逻辑与运算只有与的两边都是1, with the result is 1

Aa=$ (((66+3) *3/2)) #小括号可以调整运算优先级

Environment variable configuration file:

Source Configuration file


. Configuration file

The environment variable configuration file mainly defines the system default environment variables that are in effect for the operating environment of the system, such as the default environment variables such as path, histsize, PS1, hostname, etc.

environment variable configuration file






The role of/etc/profile

User variable

LogName variable

Mail variables

Path variable

Hostname variable

Histsize variable



The role of ~/.bash_profile

Calling the ~/.BASHRC file

Add the directory "$HOME/bin" after the PATH variable

environment variable profile in effect when logging off


Other configuration files


Shell Login Information

Local terminal welcome information:/etc/issue
Escape character Role
\d Show current system date
\s Show operating system name
\l Display the landing terminal
\m Display hardware architecture
\ n Display host Name
\o Show Domain name
\ r Show Kernel version
\ t Show current system time
\u Displays the serial number of the currently logged on user

Remote Terminal welcome information:/etc/

The transfer character cannot be used in the/etc/ file

Whether this welcome message is displayed is determined by the SSH configuration file/etc/ssh/sshd_config and added to the Banner/etc/ line to be displayed (requires a restart of the SSH service)

Display welcome information after login/ETC/MOTD

The welcome message can be displayed, whether it's a local login or a remote login

Linux 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: 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.