Practice Commands

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 151

2.

1 ls command

The ls command is the most commonly used command in linux, and the ls command is an acronym for list.

Ls is used to print a list of current directories. If ls specifies a different directory, then the list of files and folders in
the specified directory will be displayed.

By using the ls command, you can view not only the files contained in the linux folder, but also file permissions
(including directories, folders, and file permissions) and directory information, and so on.

(1) Command Format

ls [OPTION]
(2) Common Parameters

Parameter Description

-all List all files in the


-a directory, including hidden
files beginning with .

In addition to the file name,


the file permissions, owner,
-l
file size, etc. are listed in
detail.
-directory displays the
-d directory as a file instead of
the file in it

–human-readable List file sizes


-h in an easy-to-understand
format (eg 1K 234M 2G)

-t Sort by file modification time

(3) Common Examples

Example 1: List the details of all the files and directories in the /home folder. You can use the following
command:

ls -a -l /home
ls -al /home

To make it easier to see the test results, we first create a test file. Here we will use the cd and touch commands.
We will learn later so that We are not explain it here. Create commands are as follows:

cd /home
sudo touch labex.txt
The two commands above perform the same result. The result is as follows:

Note the red box above, d** stands for directory, **- indicates that files, files, and directories display different
colors.

Example 2: List the contents of all the file directories starting with "d" in the current directory. You can use the
following command:
ls -l d*

Here for the sake of showcase, we create 2 test files. touch command is used here which will be explained later:

sudo touch data.txt


sudo touch date.txt

output:
Example 3: List the size of all the file directories in the /home directory in an easy -to-understand format. You can
use the following command:

ls -alh /home

(4)Questions

1. List the size of all file directories beginning with "d" in the /home directory in an easy -to-understand
format.
2. List all directories in the /home directory that begin with "s".

2.2 cd command
The cd command can be said to be the most basic command statement in Linux. Other command statements are
to be operated on using the cd command. The cd command is an abbreviation of change directory, which
switches the current directory to the specified directory.

(1) Command Format

cd [Directory ]
(2) Common Examples

Example 1: From the current directory enter into the system root directory, you can use the following command:

cd /

Example 2: From the current directory enter into the parent directory, you can use the following command:

cd ..

.. represents the parent directory


Example 3: Entering the current user's home directory from the current directory, you can use the following
command:

cd ~

~ Indicates the current user's home directory, not the same concept as the system root directory
Example 4: From the current directory into the previous directory, you can use the following command:

cd -

 Indicates last entered directory


2.3pwd command

Use the pwd command in Linux to see the full path to the "current working directory". Simply put, every time you
operate in the terminal, you will have a current working directory. When you are not sure about the current
location, pwd is used to determine the exact location of the current directory within the file system.

The pwd command is an acronym for Print Working Directory.

(1) Command Format

pwd [OPTION]
(2) Common Parameters

Parameter Description

Display actual physical path


-P
instead of using link path

When the directory is a


-L connection path, the
connection path is displayed

(3) Common Examples

Example 1: To display the path of the current directory, use the following command:

pwd

Example 2: To display the physical path of the current directory, use the following command:

pwd -P

Example 3: To display the connection path of the current directory, use the following command:

pwd -L
(4) Questions

2.3 Reference Link


Please note this tutorial is translated from an awesome Chinese blog. Refer to the blog post for a daily Linux command.
Thanks to the excellent tutorial provided by the author Peida.

Exercise 2 – mkdir, rm, mv, cp, cat, nl

1. Experiment Introduction

1.1 Experiment Content

This experiment will introduce the usage of mkdir, rm, mv, cp, cat, and nl commands in Linux commands.

1.2 Experimental Knowledge Points

 mkdir Command
 rm Command
 mv Command
 cp Command
 cat Command
 nl Command

1.3 Experiment Environment

The experimental environment used in the course is Ubuntu Linux 14.04 64 -bit version. The program will be used
in the experiment:

 Xfce terminal
2. Experiment Procedure

 mkdir
 rm
 mv
 cp
 cat
 nl

2.1 mkdir command

(1) Command Format

mkdir [options] directory


(2) Common Parameters

Parameter Description

-m --
Set permissions
mode=mode

-p --parents It can be a path name. If


some of the directories in
the path do not exist yet,
this option will
automatically create
directories that do not yet
exist, that is, multiple
directories can be created
at one time.

Each time a new directory is


-v --verbose created, information is
displayed

(3) Common Examples

Example 1: Recursively create multiple directories, you can use the following command:

mkdir -p zhou/test

Example 2: To create a directory with privilege 777, use the following command:

mkdir -m 777 zhou


Example 3: To create a directory display message, use the following command:
mkdir -vp zhou/test

(4) Questions

Try the following command and see if anything magic happens

Tree needs to be installed separately

sudo apt-get update


sudo apt-get install tree
mkdir -vp shiyanlou/{lib/,bin/,doc/{info,product}}
tree shiyanlou/

2.2 rm command

Rm is a commonly used command. The function of this command is to delete one or more files or directories in a
directory. It can also delete a directory and all files and subdirectories under it. For the link file, only the link is
deleted and the original file remains unchanged.
Rm is a dangerous command. Be careful when using it. Especially for novices, the entire system will be destroyed
in this command (for example, rm * -rf under / (root directory)). Therefore, before we implement rm, it is better to
confirm which directory we are in, and what we want to delete.

The rm command is an abbreviation for remove.

(1) Command Format

rm [options] file or directory


(2) Common Parameters

Parameter Description

Ignore nonexistent files and


-f --force
never give prompts

-i --
Make an interactive deletion
interactive

Instructs rm to recursively
-r -- delete all directories and
recursive subdirectories listed in the
parameter

-v -- Detailed display of the steps


verbose performed
(3) Common Examples

Example 1: delete the file, the system will first ask whether to delete, you can use the following command:

rm labex.txt

Example 2: Forcibly deleting files, the system no longer prompts, you can use the following command:

rm -f labex.log
Example 3: Delete all the .log files with suffixes. Before deleting them, you can use the following command:

rm *.log 或 rm -i *.log
(4)Questions

Consider what the following command does.

myrm(){ D=/tmp/$(date +%Y%m%d%H%M%S); mkdir -

2.3 mv command

The mv command's function is used to move files or change file names. It is a commonly used command on Linux
systems and is often used to back up files or directories.
The mv command decides to either rename the file or move it to a new directory based on the sec ond parameter
type (either the target file or the target directory). When the second parameter type is a file, the mv command
completes the file renaming. At this time, the source file can only have one (it can be the source directory name).
It renames the given source file or directory to a given file. Target file name. When the second parameter is an
existing directory name, there can be multiple source file or directory parameters. The mv command moves the
source files specified by each parameter to the target directory.

The mv command is an abbreviation of move.

(1) Command Format

mv [options] source file or directory target file or directory


(2) Common Parameters

Parameter Description

If you need to overwrite the


-b --back file, you will need to back it
up before overwriting.

If the target file already exists,


-f --force it will be directly overwritten
without asking

-i -- If the target file already exists,


interactive it will ask whether to cover
If the target file already exists
-u --
and the source file is new, it
update
will be updated

This option is suitable for


moving multiple source files
-t --target to a directory. At this time,
the target directory is first
and the source file is later.

(3) Common Examples

Example 1: Rename the file labex.log to zhou.log. You can use the following command:

mv labex.log zhou.log
Example 2: Move the file zhou.log to the test directory (the test directory must already exist, otherwise perform
the rename), you can use the following command:

mv zhou.log test
Example 3: Move the file a.txt to the test1 directory. If the file exists, you will be asked whether to overwrite it
before overwriting. You can use the following command:

mv -i a.txt test1

2.4 cp command

The cp command is used to copy files or directories and is one of the most commonly used commands on Linux
systems. Under normal circumstances, the shell will set an alias. When the file is copied from the command line, if
the target file already exists, it will ask whether to overwrite, whether you use the -i parameter or not. However, if
you execute cp in a shell script, there is no -i parameter that will not ask for overwriting. This shows that the
command line and the shell script perform differently.
The cp command is an abbreviation for copy.

(1) Command Format

cp [options] source file directory

cp [options] -t directory source files


(2) Common Parameters

Parameter Description

-t --target-
Specify the target directory
directory

Ask before overwriting (make


-i --
the previous -n option
interactive
invalid)

-n --no- Do not overwrite existing files


clobber (disable previous -i option)

-s -- Create symbolic links to


symbolic- source files instead of
link copying files

-f --force Forcibly copy files or


directories, regardless of
whether the destination file
or directory already exists

After using this parameter,


the file will be copied only
when the modification time
-u --update of the source file is more than
the destination file, or the
corresponding destination
file does not exist.

(3) Common Examples

Example 1: To create a symbolic link to the file labex.log zhou.log, you can use the following command:

cp -s labex.log zhou.log

Example 2: Copy all the files in the test1 directory to the test2 directory. Before overwriting, you can use the
following command:

cp -i test1/* test2
Example 3: Copy the most recently updated file from the test1 directory to the test2 directory. Before
overwriting, use the following command:
cp -iu test1/* test2
2.5 cat command

The function of the cat command is to output a file or standard input combination to standard output. This
command is often used to display the contents of a file, or to link several files together, or to read and display
content from standard input. It is often used in conjunction with redirection symbols.

The cat command is an abbreviation for concatenate.

(1) Command Format

cat option
(2) Common Parameters

Parameter Description

-A --show-all Equivalent to -vET

-b --number- Number of non-empty


nonblank output lines

-e Equivalent to -vE

-E --show- Display at the end of each


ends line
For all the output line
-n --number numbers, starting from 1
for all output line numbers

If there are more than two


-s --squeeze-
blank lines, replace it with
blank
a blank line

-t Is equivalent to -vT

-T --show- Display tab characters as


tabs ^I

-u (be ignored)

-v --show- Use ^ and M-references,


nonprinting except LFD and TAB

(3) Common Examples

Example 1: Input labex.log file with line number and input zhou.log file. You can use the following command:

cat -n labex.log > zhou.log


Example 2: Input labex.log file with line number and input zhou.log file, replace multi-line blank line with one line
output. You can use the following command:

cat -ns labex.log > zhou.log


Example 3: To reverse the contents of the zhou.log file, use the following command:

tac zhou.log

Description: tac is to overwrite cat, so its function is the opposite of cat, cat is continuously displayed on the
screen from the first line to the last line, and tac is the reverse from the last line to the first line on the screen
display.
(4) Questions

Execute the following command will output what.

2.5 nl command

The nl command is used in the linux system to calculate the line number in the file. Nl can automatically add the
line number to the output file content. The default result is slightly different from cat -n. nl can display the line
number more than the display design, including the number of bits and whether it automatically fills 0 and so on.

The nl command is an abbreviation for number of lines.

(1) Command Format

nl option

(2) Common Parameters


Parameter Description

There are two main ways to


-b
specify the line number:

Indicates that the line number


is also listed whether it is a
-b a
blank line or not (similar to cat
-n)

If there is an empty line, do


-b t not list the line number in the
empty line (default)

There are three main ways to


-n
list line numbers:

The line number is displayed


-n ln
at the far left of the screen

The line number is displayed


-n rn on the far right of its own
field, without adding 0
The line number is displayed
-n rz on the far right of its own
field, plus 0

The number of digits occupied


-w
by the row number field

(3) Common Examples

Example 1: After the labex.log file is added with the line number, the blank line without the line number can be
used as follows:

nl -b t labex.log
Example 2: After the labex.log file is added with the line number, the line number is displayed at the leftmost,
rightmost, and rightmost 0 of the screen. You can use the following command:

nl -n ln labex.log
nl -n rn labex.log
nl -n rz labex.log
Example 3: After adding the line number to the labex.log file contents, the line number is displayed at the far
right of the screen plus 0. The line number column has 3 bits. You can use the following command:

nl -n rz -w 3 labex.log

3. reference link
For the course content, please refer to the blog post for a daily Linux command. Thanks to the excellent tutorial
provided by the author Peida.

Exercise 3 – more, less, head, tail

1.1 Experiment Content


This experiment will introduce the usage of more, less, head, tail commands in Linux commands.

1.2 Experimental Knowledge Points

 more Command
 less Command
 head Command
 tail Command

1.3 Experiment Environment

The experimental environment used in the course is Ubuntu Linux 14.04 64 -bit version. The program will be used
in the experiment:

 Xfce terminal

2. Experiment Procedure

 more
 less
 head
 tail
2.1 more command

The more command, which is similar in function to cat , is to display the contents of the entire file from top to
bottom on the screen. The more command displays page by page, allowing users to read page by page. The most
basic command is to press the space bar to display on the next page, and press the b button to go back to the
next page. There is also a search string function. The more command reads the file from front to back, so the
entire file is loaded at startup.

(1) Command Format

more [option] file


(2) Common Parameters

Parameter Description

+n Start from n line

Define the screen size as n


-n
lines

Search for the pattern before


each file is displayed, then
+/pattern
start from the first two lines of
the string

Clear the screen from the top


-c
then show
Prompt "Press space to
-d continue, 'q' to quiet", disable
the ring function

Foil the file by clearing the


-p window instead of scrolling,
similar to the -c option

Displaying consecutive blank


-s
lines as one line

Remove the lower line from


-u
the contents of the file

(3) Common operations

symbol Description

= Output the current line number

q Exit more

space bar Scroll down one screen

b Return to previous screen


(4) Common Examples

Please create a file labex.log with the following contents:

2014-11-5 a
2014-11-5 b
2014-11-5 c
2014-11-5 d
2014-11-5 e
2014-11-5 f
2014-11-5 g
2014-11-5 h
2014-11-5 e
2014-11-5 a
2014-11-5 b
2014-11-5 c
2014-11-5 d
2014-11-5 e
2014-11-5 f
2014-11-5 g
2014-11-5 h
2014-11-5 a
2014-11-5 b
2014-11-5 c
2014-11-5 d
2014-11-5 e

Example 1: To display the contents of the labex.log file from the fifth line, use the following command:

more +5 labex.log
Example 2: Find the first line of the "g" string from the labex.log file, and display the output starting from the
first two lines. Use the following command:

more +/g labex.log


Example 3: To set the number of lines per screen to 5, use the following command:

more -5 labex.log

Example 4: Using the ll and more commands to display the /etc directory information, you can use the following
command:

ll /etc | more -10


Each page shows 10 file information. Pressing Ctrl+F or Space will display the next 10 file information.
2.2 less command

The less tool is also a tool for pagination of files or other output. It should be said that linux is an orthodox tool
for viewing the content of files and is extremely powerful.

(1) Command Format

less [option] file


(2) Common Parameters

Parameter Description

When the file is displayed, it


-e
leaves automatically

Forces the opening of special


files, such as peripheral code
numbers, directories, and
-f
binary files. When the file is
displayed, it leaves
automatically

-i Ignore case when searching

Shows a percentage like the


-m
more command
Display the line number of
-N
each line

Display continuous empty


-s
behavior

(3) Common operations

symbol Description

/string Search for "string" down

?string Search for "string" upwards

Repeat previous search


n
(related to / or ?)

Reverse the previous search


N
(related to / or ?)

b Turn a page forward

d Turn half a page backward


q Exit less command

space bar Turn back one page

Up arrow Flip up one line

Down
Flip down one line
arrows

(4) Common Examples

Example 1: Display the contents of the labex.log file and display the line number. You can use the following
command:

less -N labex.log
Example 2: Display the contents of the labex.log file, the search string "labex", using the following command:

less labex.log
/labex
Example 3: ps checks the process information and displays it through less pages. You can use the following
command:

ps -f | less
The difference between less and cat and more

Cat command function: used to display the contents of the entire file, used alone without page turning function.
Therefore, it is often used with the more command. The cat command also has the function of combining several
files into one file.

More Command Function: Allows the screen to pause when a full page is displayed. Press the space bar to
continue to display the next screen, or press the q button to stop the display.

The less command function: The use of the less command is similar to the more command. It can also be used to
browse more than one page of files. The difference is that the less command can use the up and down keys to
scroll through files, in addition to pressing the space bar to display files down. When you want to end browsing,
just press q under the ":" prompt of the less command.

In fact, the three commands except the cat command have the function of merging files, the rest of the functions
are similar, but they are different from the browsing habits and display methods.

2.3 head command

The head command is as easy to understand as its name is. It is mainly used to display the beginning of the file to
the standard output. The default head command prints the first 10 lines of its corresponding file.

(1) Command Format

head option
(2) Common Parameters
Parameter Description

-q Hidden file name

-v Display file name

-c Display bytes

-n The number of rows displayed

(3) Common Examples

Example 1: To display the first 5 lines of the lqbex.log file, use the following command:

head -n 5 labex.log

Example 2: To display the first 5 lines of the labex.log and zhou.log files, use the following command:

head -n 5 labex.log zhou.log


Example 3: To display the contents of the last 5 lines in the labex.log file, use the following command:

head -n -5 labex.log
2.4 tail command

The tail command is mainly used to display the contents of the specified file. Commonly used to view log files.

(1) Command Format

tail option
(2) Common Parameters
Parameter Description

-f Loop reading

Do not display processing


-q
information

Display detailed processing


-v
information

-c Display bytes

-n The number of rows displayed

(3) Common Examples

Example 1: To display the last 5 lines of the labex.log file, use the following command:

tail -n 5 labex.log
Example 2: The last 5 lines of the labex.log file are displayed. When new content is added to the labex.log file, it
is updated automatically. You can use the following command:

tail -n 5 -f labex.log
Ping www.labex.com >> labex.log This command pings the remote host and appends the information to the
labex.log file. The effect of & is to place this command in the background so that the labex.log file will always
have more content. Note that the ping command under Linux will always be executed and must be s topped
manually. When the ping command is executed under Windows, it will stop automatically after sending a certain
request.
Use the -f option of the tail command to output the contents of the file immediately after the file changes. tail -f
filename will display the contents of the end of filename on the screen, and not only refresh, allowing you to see
the latest file content.Also by the way, how do you view the tasks that are running in the background and how to
stop them?The jobs command can see the tasks that are running in the background. The kill command can kill a
task but use the task's id. The id of the task can be obtained by viewing the ps command.

Exercise 4 – which, whereis, locate

1.1 Experiment Content

This experiment will introduce the usage of which, whereis, and locate commands in Linux commands.

1.2 Experimental Knowledge Points

 which Command
 whereis Command
 locate Command

1.3 Experiment Environment

The experimental environment used in the course is Ubuntu Linux 14.04 64 -bit version. The program will be used
in the experiment:

 Xfce terminal
2. Experiment Procedure

 which
 whereis
 locate

2.1 which command

The role of the which command is to search for the location of the executable file in the path specified by the
PATH variable. It is generally used to confirm whether the specified software is installed in the system.

(1) Command Format

which executable file name


(2) Common Examples Example 1: To confirm whether gcc is installed, use the following command:

which gcc

Example 2: To view the path of the cd command, use the following command:
which cd

From the above display information you can see in the labex system cd is a shell function.

Then execute the which cd command on my local linux system. The result is as follows:

There is no cd command displayed in the path specified by the PATH variable. Why is it not displayed? This is
because cd is a shell built-in command, and which by default finds the directory specified in PATH. The built -in
command is not in its specified directory, so of course it must not be found.

Then there is a problem, why cd is a shell function in the labex environment, and cd i s a built-in command in
other linux environment? This is related to the bash used.

The echo $SHELL command looks at the currently used shell.


2.2 Supplementary Knowledge

What exactly is an order?

The command can be one of the following four forms:

1. Is an executable program, just like the file we have seen in the directory /usr/bin. Programs that fall into
this category can be compiled into binary files, such as those written in C and C++, or programs written in
scripting languages, such as shell, perl, python, ruby, and so on.
2. Is a command built into the shell itself. Bash supports several commands, internally called builtins. For
example, the cd command in my local environment above is a shell internal command.
3. Is a shell function. These are small-scale shell scripts that are mixed into environment variables. For
example, the cd command mentioned above is a shell function in the lab environment.
4. Is a command alias. We can define our own commands and build on other commands. The echo $SHELL
command looks at the currently used shell.

2.3 whereis command

The whereis command is mainly used to locate the executable file, source code file, and help file in the file
system. The whereis command also has the ability to search for source code, specify an alte rnate search path, and
search for unusual items.

The whereis command looks up very quickly because it isn't just looking around randomly on disk, but in a
database (/var/lib/mlocate/). This database is automatically created by the Linux system, contains in formation on
all local files, and is updated once every day by automatically executing the updatedb command. It is precisely
because this database is updated once a day, it will make the search results of whereis command sometimes
inaccurate, such as just added files may not be found.

(1) Command Format

whereis [options] file


(2) Common Parameters

Parameter Description

-b Targeting executables

-m Locate help file

-s Locating source code files

Searching for files other than


-u executables, source files, and
help files in the default path

Specify the path to the search


-B
executable

Specify the path to the search


-M
help file
Specify the path to the search
-S
source file

(3) Common Examples

Example 1: Search for the path to the gcc executable. You can use the following command:

whereis -b gcc

Example** 2: Search for the path to the gcc help file. You can use the following command:

whereis -m gcc

Example 3: Search for the path to the gcc source code. You can use the following command:

whereis -s gcc
2.4 locate command

The locate command is similar to the whereis command and they use the same database. However, the whereis
command can only search for executable files, online help files, and source code files. If you want more
comprehensive search results, you can use the locate command.

The locate command uses a very complex matching syntax that uses special characters (such as '*' and '?') to
specify which samples to look for.

(1) Command Format

locate [option](Search string)

(2) Common Parameters

Parameter Description

Quiet mode, no error message


-q
is displayed

-n Display at most n outputs

Use regular expressions to do


-r
the search

-V Display version message

(3) Common Examples


Example 1: To search for all files beginning with sh in the etc directory, use the following command:

locate /etc/sh

Note that executing this command in the labex environment may result in an error: locate cannot be executed
stat() ‘/var/lib/mlocate/mlocate.db’ : There is no such file or directory. The solution is to execute the sudo
updatedb command.
Example 2: Search for the file named lou in the etc directory. You can use the following command:

locate /etc/*lab*
Exercise 5 – find, xargs

1. Experiment Introduction

1.1 Experiment Content

This experiment will introduce the usage of the find and xargs commands in Linux commands.

1.2 Experimental Knowledge Points

 find Command
 xargs Command

1.3 Experiment Environment

The experimental environment used in the course is Ubuntu Linux 14.04 64 -bit version. The program will be used
in the experiment:

 Xfce terminal

2 Experiment Procedure

 find
 xargs
2.1 find command (1)

The main function of the find command is to traverse down the file hierarchy, match the files that meet the
conditions, and perform the corresponding operations. Under the Linux find command provides a lot of search
conditions, the function is very powerful, the corresponding learning is also more difficult.

(1) Command Format

find option [expression]


The default path is the current directory and the default expression is -print.

The expression may consist of the following components: operators, options, test expressions, and actions.

(2) Common Parameters

Parameter Description

Find command outputs


-print matching files to standard
output

The find command executes


-exec the shell command given for
the matching file
-name Find files by file name

-type Finding a type of file

Using this option to make the


find command not lookup in
the currently specified
-prune
directory. If you use the -
depth option, -prune will be
ignored by the find command.

-user Find files by owner of the file

Find files by the group they


-group
belong to

Find the file according to the


file's change time, -n means
the file change time is less
-mtime -n than n days, +n means the file
+n change time is now greater
than n days, the find
command also has -atime and
-ctime options

Other commands Command options and expressions can be seen in the figure below.
(3) Common Examples

Example 1: To print a list of file directories in the current directory, use the following command(Only the first 10
rows are displayed):

find . -print | head -10

Example 2: Print all the file names ending in .txt in the current directory, you can use the following command (the
screenshot shows only part):

find . -name "*.txt" -print | head -10

The -iname option works the same as the -name option except that -iname ignores case letters.
Example 3: To print all file names ending with .txt or .pdf in the current directory, use the following command
(screenshot shows only part):

find . \( -name "*.pdf" -or -name "*.txt" \)


Example 4: Print all file names in the current directory that do not end with .txt. You can use the following
command:

find . ! -name "*.txt"

2.2 find command (2)

Here's how to find matching files based on file type, permissions, owner, and operator.

According to the file type to find the file, use the -type option, the common find file type is shown in the
following table.

File type Description

b Block device file

c Character device file


d Directory

f Ordinary file

l Symbolic link

Find files based on file permissions using the -perm option. The owner uses the -user option.

In addition, the find command can create more complex logical relations through logical operators. For example,
the operator -or is used in Example 3 of the find command (1). The logical operators for the find command are
shown in the following table.

Operators Description

Matches if the test files on


both sides of the operator are
-and true. Can be abbreviated as -a.
Note that -and is used by
default if no operator is used

Match if any of the test


conditions on both sides of
-or
the operator are true. Can be
abbreviated as -o
Match if the test condition
following the operator is false.
-not
Can be abbreviated as an
exclamation point (!)

Combining test conditions and


operators to form larger
expressions. This will always
control the logic calculation
priority. By default, find
commands are evaluated from
left to right. It is often
necessary to override the
default job search order to get
the desired result. Even if not
necessary, sometimes
() including the combined
characters is helpful for
improving the readability of
the command. Note that
because parentheses have
special meaning to the shell,
when using them on the
command line, they must be
enclosed in parentheses
before they can be passed as
arguments to the find
command. Usually backslash
characters are used to escape
parentheses

(1) Common Examples

Example 1: To print all symbolic links ending in .txt in the current directory, use the following command:

find . -type l -name "*.txt" -print

Example 2: Print all php files with permissions of 777 in the current directory (php files on web servers generally
need execute permission). You can use the following command:
find . -type f -name "*.php" -perm 777

Example 3: To print all files owned by the root user in the current directory, use the following command:

find . -type f -user root


Example 4: Print all files whose permissions under the current directory are not 777 and 664. You can use the
following command:

find . -type f \( ! -perm 777 -and ! -perm 644 \)


2.3 find command (3)

The following describes how to use the -exec option of the find command to perform the specified action
command on the found file.

(1) Common Examples

Example 1: To find all the php files in the current directory and display their detailed information, you can use
the following command:

find . -name "*.php" -exec ls -l {} \;


-exec is the action that the find command performs on the found file. This action is to execute the command on
the found file. The above command is ls -l {}. Here to explain {} and ;, {} It is actually a placeholder, in the
implementation of the find command will continue to be replaced by the currently found file, which is equivalent
to "ls -l found file". And ; is the end of the -exec command, because the command behind -exec must end with ;
but; has a special meaning in the shell and must be escaped, so written as ;.

Example 2: In the labex environment, there are many c language code files written by ourselves. Now we want to
download all the c language code files. If one or the other is very troublesome, we can find all the c language
code files first, and then Write the contents of these files to a file, download the file, you can use the following
command:

find . -name "*.c" -exec cat {} \; > all.c


Example 3: By default, only one command can be used after -exec. If you want multiple commands, you can write
multiple commands to the script file. Then use this script in -exec. You can use the following command:

find . -name "*.c" -exec ./command.sh {} \;

Script content:

#! /bin/bash
ls -l $1 # $1 Indicates the first parameter
cat $1
xargs command

We can use pipe to redirect stdout (standard output) of one command to stdin (standard input) of another
command. However, some commands can only receive data in the form of command line parameters and cannot
receive data streams through stdin. In this case, data cannot be redirected to these commands through pipes.

In this case, xargs can play its role. The xargs command can receive input from standard input and convert the
input to a specific parameter list.

(1) Command Format

command | xargs Options

The xargs command should immediately follow the pipeline operator because it uses the standard input as the
primary source data stream.

(2) Common Parameters

Parameter Description

Specify the maximum number


-n
of parameters per row
-d Specify separator

(3) Common Examples

Example 1: Converting multi-line input to single-line output can use the following command:

cat a.txt | xargs

Example 2: To convert a single-line input to multiple lines of output, use the following command:

echo "1 2 3 4 5 6 7" | xargs -n 3

Example 3: Convert single-line input to multi-line output. Specify the separator as i. You can use the following
command:
cat b.txt | xargs -d i -n 3

Example 4: Find all c code files in the current directory and count the total number of lines. You can use the
following command:

find . -type f -name "*.c" | xargs wc -l


Exercise 6- wc,grep,Regular expression

1.1 Experiment Content

This experiment will introduce the usage of the wc and grep commands in Linux commands.

1.2 Experimental Knowledge Points


 wc Command
 grep Command

 Regular expression

1.3 Experiment Environment

The experimental environment used in the course is Ubuntu Linux 14.04 64-bit version. The program will be used
in the experiment:

 Xfce terminal

2. Experiment Procedure

 wc
 grep

2.1 wc command

The wc command is a statistical tool that is used to display the number of lines, words, and bytes contained in a
file.
The wc command is an abbreviation for word count.

(1) Command Format

wc option
(2) Common Parameters

Parameter Description

-c Statistics bytes

-l Statistics rows

Number of characters
-m counted. This flag cannot be
used with the -c flag

The number of statistical


words, a word is defined as a
-w
string separated by blanks,
tabs or newline characters

Print the length of the longest


-L
line

(3) Common Examples


Example 1: Count the number of bytes, lines, and characters of a file. You can use the following command:

wc -c c.txt
wc -l c.txt
wc -m c.txt

One line break per line here is also a character, the word (32) + space (4) + line break (1) = 37.

Example 2: Count the number of bytes, lines, and characters of a file, print only numbers, and do not print the file
name. You can use the following command:

cat c.txt | wc -c
cat c.txt | wc -l
cat c.txt | wc -m
Example 3: To count the number of commands in the /bin directory, use the following command:

ls /bin | wc -l

2.2 grep command

Grep is a very powerful command for finding matching text in a file, accepting regular expressions and wildcards,
and using multiple grep command options to generate output in various formats.

Grep works like this, searching for a string template in one or more files. If the template includes spaces, it must
be referenced and all strings after the template are treated as file names. The search results are sent to the
standard output without affecting the original file content.

Grep can be used for shell scripts because grep states the status of the search by returning a status value, 0 if the
template search succeeded, 1 if the search was unsuccessful, and 2 if the searched file did not exist. We can use
these return values to perform some automated text processing.
(1) Command Format

grep [options] pattern [file]


(2) Common Parameters

Parameter Description

Calculate the number of


-c 'search string' (ie pattern)
found

Ignore case differences, so


-i
case is considered the same

-n Output line number

Reverse selection, print


-v
mismatched lines

-r Recursive search

-- Add a color display to the


color=anto found keyword section

(3) Common Examples


Example 1: Take out the root line in the /etc/passwd file, and add the color to the keyword. You can use the
following command:

grep "root" /etc/passwd --color=auto


cat /etc/passwd | grep "root" --color=auto

Example 2: To remove the root and nologin lines from the /etc/passwd file, use the following command:

grep -v "root" /etc/passwd | grep -v "nologin"


Example 3: In the current directory recursive search file contains main () file, often used to find some function in
which source code file, you can use the following command:

grep -r "main()". head -10

2.3 Regular expression and grep commands


A regular expression is a symbolic representation that is used to identify text patterns. To some extent, they are
similar to shell wildcards that match file and path names, but they are larger. Many command -line tools and most
programming languages support regular expressions to help solve text manipulation problems.

Regular expression metacharacters consist of the following characters:

^$.[]{}-?*+()|\

Regular
Description Example
expression

^labex
matches
Line start
^ rows
marker
starting
with labex

$labex
matches
End of line
$ rows
marker
ending with
labex

a.c matches
Match any abc, aac but
.
character does not
match abbc
Match any
ab[cd]
character
[] matches
contained in
abc or abd
[Character]

1[^01]
Match any
matches
character
[^] 12,13 but
except [ ^
does not
character]
match 10,11

Match any
character [1-5] Match
[-] within the any number
specified from 1 to 5
range

[0-9]{2}
matches
any two-
Match the digit
{n} previous item number,
n times which is
equivalent
to [0-9][0-
9]
[0-9]{2,}
The previous
matches a
item needs to
{n,} digit with
match at least
two or
n times
more digits

Specify the
minimum and [0-9]{2,5}
maximum matches
number of any number
{n,m}
times the from two
previous item digits to
needs to five digits
match

Match the lab?ex


? previous item matches
1 or 0 times labex, laex

Match the lab*ex


previous item matches
*
0 or more laex, labex,
times labeex

+ Match the lab+ex


previous item matches
one or more labex,
times labbex

Create a Ma(in)?
() substring for matches ma
matching or main

Dec(1st |
Match | Any 2nd)
| of the two matches
sides Dec 1st or
Dec 2nd

Escape special a\+b


\ characters matches
above a+b

(1) Common Examples

Example 1: Use the Linux system's own dictionary to find a five-letter word, the third letter is j, the last letter is r,
/usr/share/dict directory to store the dictionary file,If you do not have a dictionary, you can create your own test
file, you can use the following command:

grep '^..j.r$' linux.words


Example 2: Verify the fixed phone and print the eligible phone. The format of the fixed phone is basically the area
code with 0 + connector "-" + phone number, and there may be an extension number, and the area code has 3, 4
digits. The phone number has 7 and 8 digits, you can use the following command:

grep "^0[0-9]{2,3}-[0-9]{7,8}(-[0-9]{3,4})?$" telphone.txt

Area code: preceding 0, followed by 2-3 digits: 0[0-9]{2,3}

Phone number: 7-8 digits: [0-9]{7,8}

Extension number: Generally 3-4 digits: [0-9]{3,4}


Note that there is no matching output when executing the following command. This is because without the -E
option, why isn't this case? Why? This is because grep treats it as a shell wildcard, not a regular expression
metacharacter.

Exercise 7- cut,paste,tr

1.1 Experiment Content

This experiment will introduce the usage of the cut, paste, and tr commands in Linux commands.
1.2 Experimental Knowledge Points

 cut Command
 paste Command
 tr Command

1.3 Experiment Environment

The experimental environment used in the course is Ubuntu Linux 14.04 64-bit version. The program will be used
in the experiment:

 Xfce terminal

2. Experiment Procedure

 cut
 paste
 tr

The cut command is a gadget that splits the text by columns, and it can specify the delimiter that separates each
column.
2.1 cut command

If a row of data contains more than one field (multiple columns) and you now want to extract one or more of
them, this is the cut command.

(1) Command Format

cut [option](file name)


(2) Common Parameters

Parameter Description

-b Split in bytes

-c Split by character

Custom separator, defaults


-d
to tabs

-f Custom fields

Extract entire text lines


--
except those specified by
complement
the -c or -f options

(3) Common Examples


Example 1: To remove the first and third columns in the student.txt file, use the following command:

cut -f 1,3 -d ' ' student.txt

Example 2: To remove the first column in the student.txt file, use the following command:

cut -f 1 -d ' ' student.txt


Example 3: To remove the first three columns in the student.txt file, use the following command:

cut -f 1-3 -d ' ' student.txt

Example 4: Remove the other columns in the student.txt file except for the first column, you can use the
following command:

cut -f 1 -d ' ' student.txt --complement


Example 5: Give any string str, remove its last character, you can use the following command:

num=$(echo -n $str | wc -c)


echo -n $str | cut -b $num
# or
echo -n $str | cut -b `echo -n $str | wc -c`

2.2 paste command

The function of the paste command is exactly the opposite of cut. Instead of extracting text columns from the file,
it adds one or more text columns to the file. It reads multiple files and then combines the fields in each file into a
single text stream that is input to the standard output.

(1) Command Format

paste [option](file name)


(2) Common Parameters
Parameter Description

Merge each file into rows


-s
instead of lines

Custom separator, defaults to


-d
tabs

(3) Common Examples

Example 1: Splicing the contents of student.txt and telphone.txt files by column, you can use the following
command:

paste student.txt telphone.txt


Example 2: Splicing the contents of the student.txt and telphone.txt files by columns. Specify the separator as ':'.
You can use the following command:

paste student.txt telphone.txt -d ':'


Example 3: Splicing the contents of the student.txt and telphone.txt files into a single line, you can use the
following command:

paste -s student.txt telphone.txt

2.3 tr command

The tr command is often used to change characters. We can think of it as a character -based search and replace
operation. Word change is the process of converting characters from one letter to another. Tr Replaces, reduces,
and/or deletes characters from standard input and writes the result to standard output.

Tr can only pass stdin (standard input) and cannot accept input via command line arguments.
Tr is the abbreviation for translate.

(1) Command Format

Tr [options] SET1 SET2


Map input characters from stdin from SET1 to SET2 and write their output to stdout (standard output). SET1 and
SET2 are character classes or character sets. If the lengths of the two character sets are not equal, then SET2 will
continue to repeat its last character until it has the same length as SET1. If the length of SET2 is greater than SET1,
all the characters that exceed SET1 in SET2 are ignored.

(2) Common Parameters

Parameter Description

Delete content that matches


-d
SET1 and do not replace

(3) Common Examples

Example 1: To convert the input characters to lowercase, use the following command:

echo 'THIS IS SHIYANLOU!' | tr 'A-Z' 'a-z'

Example 2: To delete the numbers in the input characters, use the following command:
echo 'THIS 123 IS S1HIY5ANLOU!' | tr -d '0-9'

Example 3: An interesting use of the tr command is to perform ROT13 text encoding. ROT13 is a trivial type of
encryption based on a simple replacement password. Calling ROT13 "encryption" is generous, and "text blurring"
is more accurate. Sometimes it is used to hide potential attack content in text. This method is simply to move
each character forward by 13 in the alphabet. Because the number of bits moved is half of the possible 26
characters, executing this algorithm again on the text returns to its original form. You can use the following
command:

#encryption
echo 'shiyanlou' | tr 'a-zA-Z' 'n-za-mN-ZA-M'
fuvlnaybh
#Decryption
echo 'fuvlnaybh' | tr 'a-zA-Z' 'n-za-mN-ZA-M'
shiyanlou
Exercise 8 - sort,uniq,join

1.1 Experiment Content

This experiment will introduce the usage of the sort, uniq, and join commands in Linux commands.

1.2 Experimental Knowledge Points

 sort Command
 uniq Command
 join Command

1.3 Experiment Environment

The experimental environment used in the course is Ubuntu Linux 14.04 64-bit version. The program will be used
in the experiment:

 Xfce terminal

2. Experiment Procedure

 sort
 uniq
 join

2.1 sort command

When dealing with text files, you can't avoid sorting. That's because sorting can play a big role in text processing
tasks. The sort command helps us sort text files and stdin. Usually, it combines other commands to generate the
desired output.

(1) Command Format

sort [option](file name)


(2) Common Parameters

Parameter Description

Sort based on the length of


the string, use this option to
-n allow sorting based on
numeric values instead of
alpha values

-k Specify sort keywords

By default, the entire row is


-b sorted, starting with the first
character of each line. This
option causes the sort
program to ignore spaces at
the beginning of each line,
sorting from the first nonwhite
space character

Only merge multiple input


-m
files

Sort in reverse order, results


-r are sorted in descending
order, not ascending

Custom separator, defaults to


-t
tabs

(3) Common Examples

Example 1: List the top 10 directory files in the /usr/share/ directory. You can use the following command:

du -s /usr/share/* | sort -nr | head -10

The du -s /usr/share/* command displays the disk space for all files and directories in the /usr/share/ directory.
The directory contains subdirectories and files under the directory.
Example 2: The ls command can display the detailed information of the files in the directory, including the size of
the space used. However, unlike the du command, the ls command does not calculate the size of the
subdirectories and files in the directory. The ls display format is as follows:

-rwxrwxrwx 1 root root 542 mar 19 13:18 test.php

Now you want to sort the space usage size field in the output of the ls command, you can use the following
command:

ls -l /usr/bin/ | sort -nr -k 5 | head -10


Example 3: First look at the following example:

Since 11 starts with 1, it is smaller than 5, so it is ahead of 5. Sorting can now be sorted by a custom sort field.
Use the following command to solve.

sort -k 1,1 -k 2n data.txt


The first -k option indicates that only the first field is sorted, 1,1 means "starting at and ending at the first field."

The second -k option 2n indicates that the second field is sorted numerically.

There is also a format, such as -k 3.4n, which represents the fourth character from the third field, sorted
numerically.

The syntax of the -k option is as follows:

[ FStart [ .CStart ] ][ Modifier ] [ , [ FEnd [ .CEnd ] ][ Modifier ] ]


This grammar format can be divided into two parts by the comma (","), the Start part and the End part.

First instill a thought for you, that is, "If you do not set the End part, then think End is set to the end of the line."
This concept is very important, but often you will not value it.

The Start section also consists of three parts, where the Modifier section is an option section similar to n and r.
We focus on the FStart and CStart in the Start section.

FStart.CStart, where FStart is the field that represents the use, and CStart represents the "first character to sort"
from the first few characters in the FStart field. CStart can be omitted. If omitted, it means starting from the
beginning of this field. The -k 5 in the previous example is an example that omits CStart.
Similarly, in the End section, you can set FEnd.CEnd. If you omit .CEnd, it means that the end is "end of field",
which is the last character of this field. Or, if you set CEnd to 0 (zero), it also indicates the end of th e field to the
end of the field.

2.2 uniq command

The uniq command is often used in conjunction with the sort command. Uniq accepts an ordered list of data from
standard input or a single file name parameter, and by default, removes any duplicate rows f rom the data list.

Uniq can only be used for sorted data input, so uniq uses either piped or sorted files as input and is always used
in conjunction with the sort command in this way.

The uniq command is an abbreviation for unique .

(1) Command Format

uniq [option][file name]


(2) Common Parameters

Parameter Description

Prepend each line with a prefix


number indicating the number
-c
of occurrences of the
corresponding line
-d Only output duplicate rows

-u Only show unique rows

-D Display all duplicate rows

Skip the first n columns when


-f
comparing

-i Case-insensitive comparisons

Skipping the first n characters


-s
when comparing

Do not compare the contents


-w of the nth character after each
line

(3) Common Examples

Example 1: To find out all the same commands in the /bin directory and the /usr/bin directory, use the following
command:

ls /bin /usr/bin | sort | uniq -d


Example 2: The contents of the existing documents are as follows. The content in the red box indicates the area
code. The total number of each area code must now be counted.

Implementation ideas: First, sort the information of each row by area code, and then use the uniq command to
repeat the statistics for the area code. Use the command as follows:

sort -k 4.1n student.txt | uniq -c -f 3 -w 2


Sort -k 4.1n means to sort the first character of the fourth field numerically.

Uniq -c -f 3 -w 2 -f 3 means to skip the comparison of the first three columns, so now only the last column is
left. -w 2 means that the contents after the second character are not compared. Why is 2? Because skipping the
first three columns does not skip the space separator before the last column, there is a space before the area
code.

2.3 join command

The join command is similar to paste , which adds columns to the file, but it uses a unique approach. A join
operation is usually associated with a relational database in which data from multiple tables sharing common key
fields is combined to obtain a desired result. This join command does th e same thing and it combines data from
multiple shared key domain based files.

In layman's terms, it is to connect the two lines with the same field in the two files, that is, to splice the
corresponding line into one line according to a common column in the two files.

(1) Command Format

join [option] file 1 file 2


(2) Common Parameters
Parameter Description

Equivalent to -1 FIELD -2
-j FIELD FIELD,-j specifies a field as a
match field

-1 FIELD Match with FIELD field in file1

-2 FIELD Match with FIELD field in file2

Custom separator, defaults to


-t
tabs

(3) Common Examples

Example 1: The first field in two files as a match field, connect two files, you can use the following command:

join a.txt b.txt


Example 2: Specify the third field of the two files as the match field, connect two files, you can use the following
command:

join -1 3 -2 3 c.txt d.txt


As you can see from the above results, an error occurred when executing the join command on the contents of
the a.txt and b.txt files. This is because the join command, like the uniq command, can only be used for sorted
data.

Exercise 9 - comm,diff,patch

1.1 Experiment Content

This expriment will introduce the usage of the comm, diff, and patch commands in Linux commands.
1.2 Experimental Knowledge Points

 comm Command
 diff Command
 patch Command

1.3 Experiment Environment

The experimental environment used in the course is Ubuntu Linux 14.04 64-bit version. The program will be used
in the experiment:

 Xfce terminal

2. Experiment Procedure

 comm
 diff
 patch

It is often helpful to compare the contents of text files. This is especially important for system administrators and
software developers. A system administrator may, for example, need to compare existing configuration files with
previous versions to diagnose a system error. Similarly, a programmer often needs to check the program's
changes.
2.1 comm command

The comm command will compare the two files already sorted line by line. The display consists of 3 columns:
Column 1 is the row found only in the first file, Column 2 is the row found only in the second file, and Column 3 is
the common row of both files.

Note that the comm command, like the join and uniq commands, can only be used for data that has already been
sorted.

(1) Command Format

comm [option] file 1 file 2


(2) Common Parameters

Parameter Description

Does not output file 1 unique


-1
lines

Do not output file 2 unique


-2
lines

Do not output lines common


-3
to both files

(3) Common Examples

Example 1: Compare the contents of file1.txt and file2.txt and use the following command:
comm file1.txt file2.txt

Example 2: Compare the contents of two files, file1.txt and file2.txt, to display only the contents of the two files.
Use the following command:

comm -12 file1.txt file2.txt


2.2 diff command

Like the comm command, the diff command is used to monitor the differences between files. However, diff is a
more sophisticated tool that supports many output formats and can handle many text files at a time. Software
developers often use the diff program to check for changes between source code versions of different programs.
Diff can recursively examine the source directory, often referred to as the source tree. A common use case for diff
programs is to create a diff file or patch that will be used by other programs, such as the patch program (which
we'll talk about later) to convert files from one version to another.

Diff prints every line change on the command line, and diff is an integral part of version control tools such as svn,
cvs, git, and so on.

The diff command is an abbreviation for differential.

(1) Command Format

diff [option] file


(2) Common Parameters

Parameter Description

Context mode, showing all the


-c text and marking out
differences

Unified mode to display


-u different contents of files in a
consolidated manner
Only text files will be
-a
compared line by line

When comparing directories, if


file A only appears in a
directory, the default is: Only
-N
in directory. If you use the -N
parameter, diff compares file
A with a blank file

Recursively compare files


-r
under a directory

(3) Common Examples

Example 1: Display the difference between file1.txt and file2.txt. You can use the following command:

diff file1.txt file2.txt


"1d0" in the above result display indicates that the file1.txt file has the first line more than the file2.txt file, and
"4c3,4" indicates that the fourth line of the file1.txt file is different from the third and fourth lines of the file2.txt
file. .

There are three tips for the diff's normal display format:

 a - add
 c - change
 d - delete
Example 2: From the display result of the above example one, we can know that the difference between the two
files file1.txt and file2.txt is not easy to see, you can use the context mode display, you can use the following
command:

diff -c file1.txt file2.txt

This output begins with two file names and their time stamps. The first file is marked with an asterisk, and the
second file is marked with a dash. Throughout the rest of the list, these tags will represent the files they represent.

*** 1,4 *** Indicates the first to fourth line of text in the first file.
--- 1, 4 --- Represents the first to fourth lines of text in the second file.

Three special characters:


+ Add line, this line will appear in the second file, not the first file

- Delete line, this line will appear in the first file, not in the second file

! Change the line, two versions of a text line will be displayed, each version will appear in the respective part of
the change group

These special characters are easy to confuse, and you can actually remember one thing at a time: The pu rpose of
all operations is to turn the first file into a second file.

Example 3: Check the differences between the two files, file1.txt and file2.txt. Use the unified mode to display the
following commands:

diff -u file1.txt file2.txt

The most significant difference between context mode and unified mode is the elimination of duplicated contexts,
which makes the output of unified mode shorter than the output of context mode.
@@ -1,4 +1,4 @@ Indicates the line of text in the first file described in the change group and the line of text in
the second file.

Special characters:

 + Add this line to the first file


 - Delete this line in the first file

2.3 patch command

The patch command is used to apply the changes to the text file. It accepts output from the diff program and is
usually used to convert older file versions to newer file versions. Let us consider a well -known example. The Linux
kernel was developed by a large, loosely-organized team of contributors who submitted a fixed number of
changes to the source package. This Linux kernel is made up of millions of lines of code, though each contributor
makes very few changes each time. For a contributor, it makes no sense to send the entire kernel source tree to
each developer for every modification. Instead, submit a diff file. A diff file contains the difference between the
previous kernel version and the new version with contributor modifications. A recipient then uses the patch
program to apply these changes to his own source tree. Using the diff/patch combination provides two major
advantages:

1.A diff file is very small, compared to the size of the entire source tree.

2.A diff file succinctly shows the changes, allowing reviewers of program patches to quickly evaluate it.

Of course, diff/patch works on any text file, not just source files. It also applies to configuration files or any other
text.
Prepare a diff file for the patch command. The GNU documentation recommends using the diff command like so:

diff -Naur old_file new_file > diff_file

The old file and new file sections are not single files or directories that contain files. This r option supports
recursive directory trees.

(1) Command Format

patch [options] patch file


(2) Common Parameters

Parameter Description

-p num Ignore several layers of folders

If you find an empty file,


-E
delete it

-R Canceled patches

(3) Common Examples

Example 1: Generate the diff file of file1.txt and file2.txt, and then use the patch command to update the file1.txt
file. You can use the following command:

diff -Naur file1.txt file2.txt > patchdiff.txt


patch < patchdiff.txt

Example 2: To cancel the patch played in the above example, you can use the following command:

patch -R < patchdiff.txt


Exercise 10 - df,du,time

1.1 Experiment Content

This experiment will introduce the usage of the df, du, and time commands in Linux commands.

1.2 Experimental Knowledge Points

 df Command
 du Command
 time Command

1.3 Experiment Environment

The experimental environment used in the course is Ubuntu Linux 14.04 64-bit version. The program will be used
in the experiment:

 Xfce terminal
2. Experiment Procedure

 df
 du
 time

2.1 df command

The function of the df command in linux is to check the disk space usage of the linux server's file system. You can
use this command to find out how much space your hard disk is occupying, and how much space is left.

The df command is an acronym for disk free.

(1) Command Format

df [option] file
(2) Common Parameters

Parameter Description

-a All file system list


-h Easy to read display

-i Show inode information

-T File system type

Only show disk information


-t
for the selected file system

Does not display disk


-x information for the selected
file system

(3) Common Examples

Example 1: To display the disk usage, use the following command:

df
Example 2: To display the disk usage in inode mode, you can use the following command:

df -i

Example 3: To list the file system type, use the following command:

df -T
Example 4: To display the specified type of disk, use the following command:

df -tT ext4

2.2 du command

The function of the df command in linux is to check the disk space usage of the linux server's file system. You can
use this command to find out how much space your hard disk is occupying, and how much space is left.

The df command is an acronym for disk free.


(1) Command Format

df [option] file
(2) Common Parameters

Parameter Description

-a All file system list

-h Easy to read display

-i Show inode information

-T File system type

Only show disk information


-t
for the selected file system

Does not display disk


-x information for the selected
file system

(3) Common Examples

Example 1: To display the disk usage, use the following command:


df

Example 2: To display the disk usage in inode mode, you can use the following command:

df -i

Example 3: To list the file system type, use the following command:

df -T
Example 4: To display the specified type of disk, use the following command:

df -tT ext4

2.3 time command

The time command is often used to measure the running time of a command, including the actual time, the
process spent in user mode, and the process spent in kernel mode.

Actual time: The time from execution of the command command line to the end of the run.
User mode usage time: the user's CPU time spent to complete the command execution, that is, the sum of the
execution time of commands in the user mode.

Kernel-state usage time: The system CPU time spent executing the command, that is, the sum of the execution
time of the command in the core state.

(1) Command Format

time command
(2) Common Examples

Example 1: To measure the running time of the date command, use the following command:

time date

From the above results can be: the actual running time is 0.002s, the user cpu time is 0.000s, the system cpu time
is 0.000s.

Among them, the sum of the user CPU time and the system CPU time is the CPU time, that is, the sum of the time
the command occupies the CPU. The actual time is greater than the CPU time, because Linux is a multitasking
operating system, and often the system has to deal with other tasks when executing a command.
Example 2: To save the execution result of the time command to a file, use the following command:

{ time date; } 2>1.txt


(time date) 2>2.txt

Time is the keyword of the shell. The shell does special processing. It will handle the command line behind the
time command as a whole. In the redirection, it is actually for the following command, the output of the time
command itself. Will not be redirected. For example, execute time date 2>3.txt, and the co ntent of 3.txt is empty.
In addition, the output of the time command is printed on the standard error output.

You might also like