Linux Shell学习(持续更新)

Shell

date

display the current time and date

cal

by default, displays a calendar of the current month.

df

see the current amount of free space on our disk drives

free

display the amount of free memory

pwd

Print name of the current working directory

cd

Change directory

Shortcut Result
cd Changes the working directory to your home directory.
cd - Changes the working directory to the previous working directory.
cd ~user_name Changes the working directory to the home directory of user_name. For example, cd ~bob will change the directory to the home directory of user “bob.”

ls

List directory contents

We can even specify multiple directories. In the following example, we list both the user’s
home directory (symbolized by the “~” character) and the /usr directory.

root@kali:~# ls /usr ~

We can also change the format of the output to reveal more detail.

root@kali:~# ls -l

Determining a File’s Type with file

[me@linuxbox ~]$ file picture.jpg
picture.jpg: JPEG image data, JFIF standard 1.01

Manipulating Files and Directories

  • cp – Copy files and directories
  • mv – Move/rename files and directories
  • mkdir – Create directories
  • rm – Remove files and directories
  • ln – Create hard and symbolic links
Wildcards
Wildcards Meaning
* matches any char
? matches any single char
[characters] Matches any character that is a member of the set characters
[!characters] Matches any character that is not a member of the set characters
[[:class:]] Matches any character that is a member of the specified class

Commonly Used Character Classes

header 1 header 2
[:alnum:] Matches any alphanumeric character
[:alpha:] Matches any alphabetic character
[:digit:] Matches any numeral
[:lower:] Matches any lowercase letter
[:upper:] Matches any uppercase letter

Using wildcards makes it possible to construct sophisticated selection criteria for file-names. Table 4-3 provides some examples of patterns and what they match

header 1 header 2
* All files
g* Any file beginning with “g”
b*.txt Any file beginning with “b” followed by any characters and ending with “.txt
Data??? Any file beginning with “Data” followed by exactly three characters
[abc]* Any file beginning with either an “a”, a “b”, or a “c”
BACKUP.[0-9][0-9][0-9] Any file beginning with “BACKUP.” followed by exactly three numerals
[[:upper:]]* Any file beginning with an uppercase letter
[![:digit:]]* Any file not beginning with a numeral
*[[:lower:]123] Any file ending with a lowercase letter or the numerals “1”, “2”, or “3”
mkdir-Create Directories
mkdir dir1 dir2 dir3
cp – Copy Files and Directories
cp item1 item2

copies the single file or directory item1 to the file or directory item2

cp Options

Option Long Option
-a –archive
-i interactive
-r –recursive
-u –update
-v –verbose
mv - Move and Rname Files
mv file1 file2
Option Long Option
-i interactive
-u –update
-v –verbose
rm - Remove Files and Directories
rm file1

-i, - r, -f(must be specifed when you delete a directory), -v

ln-Create Links

Working with Commands

  • type – Indicate how a command name is interpreted
  • which – Display which executable program will be executed
  • help – Get help for shell builtins
  • man – Display a command’s manual page
  • apropos – Display a list of appropriate commands
  • info – Display a command’s info entry
  • whatis – Display one-line manual page descriptions
  • alias – Create an alias for a command
What Exactly Are Commands?
  1. An executable program
  2. A command built into the shell itself.
  3. A shell function.
  4. An alias.
Identify Commands
  • type – Display a Command’s Type
  • which – Display an Executable’s Location
Getting a Command’s Documentation
  • help - Get Help for Shell Builtins
  • –help – Display Usage Information
  • man – Display a Program’s Manual Page
Section Contents
1 User commands
2 Programming interfaces for kernel system calls
3 Programming interfaces to the C library
4 Special files such as device nodes and drivers
5 File formats
6 Games and amusements such as screen savers
7 Miscellaneous
8 System administration commands

To specify a section number, we use man like this:

man section search_term 
apropos – Display Appropriate Commands
whatis-Display One-line Manual Page Descriptions

Creating Our Own Commands with alias

root@kali:~# alias foo='cd /usr; ls; cd -'
root@kali:~# foo
bin    include  lib32  libexec  local  share  sslsplit
games  lib      lib64  libx32   sbin   src    var
/root

They vanish when our shell session ends

Redirection

I/O redirection allows us to change where output goes and where input comes from.

Redirecting Standard Output

SurfacemandeMBP:~ surfacegentleman$ ls -l /usr/bin > ls-output.txt
SurfacemandeMBP:~ surfacegentleman$ ls
Desktop			Movies			eclipse
Documents		Music			eclipse-workspace
Downloads		Pictures		ls-output.txt
Library			Public
SurfacemandeMBP:~ surfacegentleman$ less ls-output.txt 

use the > redirection operator followed by
the name of the file.

SurfacemandeMBP:~ surfacegentleman$ less ls-output.txt 
SurfacemandeMBP:~ surfacegentleman$ ls -l /bin/usr > ls-output.txt
ls: /bin/usr: No such file or directory
SurfacemandeMBP:~ surfacegentleman$ ls -l ls-output.txt 
-rw-r--r--  1 surfacegentleman  staff  0  6 24 08:46 ls-output.txt

when we redirect output with “>”, the destination file is always rewritten from the begining

[me@linuxbox ~]$ ls -l /usr/bin >> ls-output.txt
[me@linuxbox ~]$ ls -l /usr/bin >> ls-output.txt
[me@linuxbox ~]$ ls -l /usr/bin >> ls-output.txt
[me@linuxbox ~]$ ls -l ls-output.txt
-rw-rw-r-- 1 me me 503634 2018-02-01 15:45 ls-output.txt

we use the >> redirection operator to append redirect output to a file

Redirecting Standard Error

  • 0 —— input
  • 1 —— output
  • 2 —— error
[me@linuxbox ~]$ ls -l /bin/usr 2> ls-error.txt

The file descriptor “2” is placed immediately before the redirection operator to perform
the redirection of standard error to the file ls-error.txt.

Redirecting Standard Output and Standard Error to One File

[me@linuxbox ~]$ ls -l /bin/usr > ls-output.txt 2>&1

Using this method, we perform two redirections. First we redirect standard output to the
file ls-output.txt and then we redirect file descriptor 2 (standard error) to file descriptor 1 (standard output) using the notation 2>&1.

Recent versions of bash provide a second, more streamlined method for performing this
combined redirection shown here:

[me@linuxbox ~]$ ls -l /bin/usr &> ls-output.txt

In this example, we use the single notation &> to redirect both standard output and standard error to the file ls-output.txt.

To suppress error messages from a command, we do this:

[me@linuxbox ~]$ ls -l /bin/usr 2> /dev/null

/dev/null is a system device often referred to as a bit bucket, which accepts input and does nothing
with it.

Redirecting Standard Input

cat-Concatence Files

The cat command reads one or more files and copies them to standard output like so:

[me@linuxbox ~]$ cat > lazy_dog.txt
The quick brown fox jumped over the lazy dog.
[me@linuxbox ~]$ cat < lazy_dog.txt
The quick brown fox jumped over the lazy dog.

Pipelines

Using the pipe operator | (vertical bar), the
standard output of one command can be piped into the standard input of another

[me@linuxbox ~]$ ls -l /usr/bin | less
Filters
[me@linuxbox ~]$ ls /bin /usr/bin | sort | less
uniq - Report or Omit Repeated Lines

removes any duplicates from the list.

[me@linuxbox ~]$ ls /bin /usr/bin | sort | uniq | less
wc – Print Line, Word, and Byte Counts

display the number of lines, words, and bytes
contained in files.

grep – Print Lines Matching a Pattern

When grep encounters a “pattern” in the file, it prints out the lines containing it.

ls /bin /usr/bin | sort | uniq | grep zip
  • -i, which causes grep to ignore case when performing the search (normally
    searches are case sensitive)
  • -v, which tells grep to print only those lines that do not match the pattern
head / tail – Print First / Last Part of Files

If we only want the first few lines or the last few lines,we could use head / tail.

 head -n 5 ls-output.txt
 tail -n 5 ls-output.txt

These can be used in pipelines as well:

[me@linuxbox ~]$ ls /usr/bin | tail -n 5
znew
zonetab2pot.py
zonetab2pot.pyc
zonetab2pot.pyo
zsoelim

Using the “-f” option, tail continues to monitor the file, and when new lines are appended, they immediately appear on the display.(Ctrl-c to end)

tee – Read from Stdin and Output to Stdout and Files

repeat one of our earlier examples,this time including tee to capture the
entire directory listing to the file ls.txt before grep filters the pipeline’s contents:

[me@linuxbox ~]$ ls /usr/bin | tee ls.txt | grep zip

Seeing the World as the Shell Sees It

Expansion

Pathname Expansion

The mechanism by which wildcards work is called pathname expansion.

[me@linuxbox ~]$ echo D*
Desktop Documen
Tilde Expansion

the home directory of the current user

[me@linuxbox ~]$ echo ~
/home/me
Arithmetic Expansion

Arithmetic expansion uses the following form:
$((expression))

SurfacemandeMBP:~ surfacegentleman$ echo $((2 + 2))
4
Brace Expansion

With it, we can create multiple
text strings from a pattern containing braces. Here’s an example:

SurfacemandeMBP:~ surfacegentleman$ echo Front-{A,B,C}-Back
Front-A-Back Front-B-Back Front-C-Back

what is this good for? The most common application is to make lists of files or directories to be created.

SurfacemandeMBP:Desktop surfacegentleman$ mkdir Photos
SurfacemandeMBP:Desktop surfacegentleman$ cd Photos/
SurfacemandeMBP:Photos surfacegentleman$ mkdir {2007..2009}-{01..12}
SurfacemandeMBP:Photos surfacegentleman$ ls
2007-1	2007-2	2007-6	2008-1	2008-2	2008-6	2009-1	2009-2	2009-6
2007-10	2007-3	2007-7	2008-10	2008-3	2008-7	2009-10	2009-3	2009-7
2007-11	2007-4	2007-8	2008-11	2008-4	2008-8	2009-11	2009-4	2009-8
2007-12	2007-5	2007-9	2008-12	2008-5	2008-9	2009-12	2009-5	2009-9
Parameter Expansion
Command Substitution

Command substitution allows us to use the output of a command as an expansion.

[me@linuxbox ~]$ echo $(ls)
Desktop Documents ls-output.txt Music Pictures Public Templates 
Videos

Here we passed the results of which cp as an argument to the ls command

[me@linuxbox ~]$ ls -l $(which cp)
-rwxr-xr-x 1 root root 71516 2007-12-05 08:58 /bin/cp

Quoting

The shell provides
a mechanism called quoting to selectively suppress unwanted expansions.

Double Quotes

If we place text inside it, the expansion will lose their special meaning

[me@linuxbox ~]$ ls -l two words.txt
ls: cannot access two: No such file or directory
ls: cannot access words.txt: No such file or directory

The exceptions are $, \ (backslash), and ` (back-quote).

Parameter expansion, arithmetic expansion, and command substitution still
take place within double quotes.

root@kali:~#  echo "$USER $((2+2)) $(cal)"
root 4       六月 2019         
日 一 二 三 四 五 六  
                   1  
 2  3  4  5  6  7  8  
 9 10 11 12 13 14 15  
16 17 18 19 20 21 22  
23 24 25 26 27 28 29  
30                    

By default, word-splitting looks for the presence of spaces, tabs, and newlines (linefeed
characters) and treats them as delimiters between words.

root@kali:~# echo this is a     test
this is a test

root@kali:~# echo "this is a    test"
this is a    test

Single Quotes

If we need to suppress all expansions, we use single quotes.

[me@linuxbox ~]$ echo text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER
text /home/me/ls-output.txt a b foo 4 me
[me@linuxbox ~]$ echo "text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER"
text ~/*.txt {a,b} foo 4 me
[me@linuxbox ~]$ echo 'text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER'
text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER

Escaping Characters

Sometimes we want to quote only single character.To do this, we could add a \ befor a character

Advanced Keyboard Tricks

Permissions

The actions of one user could not be allowed to crash the computer, nor could
one user interfere with the files belonging to another user.

Owners, Group Members, and Everybody Else

superuser(uid 0)

Reading,Writing, and Executing

file attributes

the first character is file type

Attribute File Type
- A regular file
d A directory
l A symbolic link
c A character special file.(device that means stream)
b A block special file.(device thar means block)

the remaining nine characters of the file attributes is file mode,represent the read , write, and execute permissions

Attribute Files Directions
r allows a file to be opened and read Allows a directory’s contents to be listed if the execute attribute is also set.
w know the meaning when you see its name Allows files within a directory to be created, deleted, and renamed if the execute attribute is also set.
x Allows a file to be treated as a program and executed. Allows a directory to be entered, e.g., cd directory.
chmod - Change File Mode

only the file’s owner or the superuser can change the mode of a file or directory

octal notation

Octal Binary File Mode
0 000
1 001 –x
2 010 -w
3 011 -wx
4 100 r–
5 101 r-x
6 110 rw
7 111 rwx
umask – Set Default Permissions
Changing Identities
su - Run a Shell with Substitute User and Group IDs
su [-[l]] [user]
  • -l

the user’s environment is loaded and the working directory is changed to
the user’s home directory

-l could be abbreviated as -

To start a shell for the superuser, we would do this:

su -
Password:

When finished, enter exit to return to the previous shell.

It’s also possible to execute a single command rather than starting a new shell.

su -c 'command'

Remember, to enclose the command in quotes.
11``11111`1

[me@linuxbox ~]$ su -c 'ls -l /root/*'
Password:
-rw------- 1 root root 754 2007-08-11 03:19 /root/anaconda-ks.cfg
/root/Mail:
total 0
[me@linuxbox ~]$
sudo – Execute a Command as Another User

The use of sudo does not require access to the superuser’s password. To authenticating using sudo, requires the user’s own password.

chown - Change File Owner and Group

change the owner and group owner of a file or directory.

chgrp - Change Group Ownership
Changing Your Password
passwd [user]`

Processes

你可能感兴趣的:(Linux)