Objective
Work on the command line
Linux shell types
- bash / bsh
- tcsh / csh (c-shell)
- ksh (korn shell)
- zsh
1 | # which shell that /bin/sh points to |
Note: Adjusting bash config files (
~/.bashrc) only affects bash
Other notes
Directory structure: virtual directory, with one single base directory (root dir)
Check shell Built-in commands
1
2
3
4
5type echo
# echo is a shell builtin
type uname
# uname is /usr/bin/unameCommon env vars
- Use
setto display active env vars - Use
unsetto reverse edit - Use
envorprintenvto view env vars
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17# default editor
EDITOR
# default screen-based editor (e.g. nano, vim)
VISUAL
# system hostname
HOSTNAME
# Primary cmdline prompt string
PS1
# current shell level
SHLVL
# user time zone
TZ- Use
PATH env var
- root path should never include current dir (
./) - Append new path to the end of path, so standard programs take precedence
- Env var: modify program behavior
Shell command tricks
-
Ctrl+R: search command history (useESCorCtrl+Gto exit) -
Ctrl+ ←/→: move one word per time -
Ctrl+K: delete cursor to end -
Ctrl+X&Backspace: delete start to cursor -
Ctrl+XE: open editor to edit commands (export EDITOR=/usr/bin/vim)
Shell history
- Clean history:
history -c - Execute command from history:
!200 - View last 10 commands:
history 10 - Display without line number:
history | cut -c 8-
Shell config
- global:
/etc/bash.bashrc -
$TERM:xterm-256color - Display all env vars:
env
Basic file editing
Many utilities do not change texts within a file, unless redirection (e.g. sed, cut)
They only display modified text to stdout
Message Digest (Integrity)
-
md5sum -
sha256sum -
sha512sum(best)
1 - Vim
Notes
-
vieditor was a Unix text editor. Vim isvi improved - 3 standard modes
- Command mode (normal)
- Insert mode (edit, entry)
- Ex mode (colon commands)
Shortcuts
Guides:
vimtutor
1 | ^ line start |
Streams, pipes, redirects
Redirection
-
>>: append (create new file if doesn’t exist) -
2>: new file with stderr -
2>>: append stderr -
&>: new file with stdout & stderr -
<<: heredoc (terminate input:Ctrl+D)
A trick: Redirect stdout to
/dev/null(get rid of data)
1 whine 2> /dev/null
tee1
2
3
4
5
6
7
8# Program:
print("hello")
# tee: store & view the output
python hello.py | tee output.txt
# append texts:
python hello.py | tee -a output.txt
Pipe
xargs: build command from stdin
-d "\n": xargs use both spaces& newlines as item delimiterse.g.
1
2
3
4
5
6
7
8# Remove all files with ~
find ./ -name "*~" | xargs -d "\n" rm
# Equals: (`: separate command)
rm `find ./ -name "*~"`
# Equals: Shell expansion (命令嵌套,可嵌套多个)
rm $(find ./ -name "*~")Output of above command is passed to
rm, as if it’s typed in the shell
Process text streams with filters
1 - Combine files
catjoinpaste
cat
1 | # tac: reverse lines |
- Number non-blank lines
(-b, --number-nonblank)- Show end of file with
$(-E, --show-end)- Compress blank lines
(-s, --squeeze-blank)
join
Need to have similarities of fields (columns) between file 1 & 2
1 | # Note: files cannot have blank lines, else will display error: |
paste
1 | # merge files line by line |
2 - Transform files
expand/unexpandodsortsplittruniq
expand / unexpand
1 | # Convert tabs to space |
od (octal dump)
1 | # Display file dump in hex |
sort
1 | # Sort by field (-k, --key=) |
- ignore case
(-f, --ignore-case)- Numeric sort
(-n, --numeric-sort)- Reverse order
(-r, --reverse)
uniq
1 | # remove duplicate lines, use with sort |
split
1 | # split by bytes (-b, --bytes=) |
tr
change individual chars from stdin
1 | # change letter h, i to H, J |
3 - Format files
fmtnlpr
fmt
1 | # No more than 80 char wide |
nl
1 | # Number all non-blank lines |
pr
1 | # prepare file for print |
4 - View files
head/tailmore/less
head / tail
1 | head -n 5 |
more / less
lessis a better version ofmore
Basic:
- Move forward:
f - Move backward:
b - Search forward:
N - Search backward:
Shift + N - Move to line 50:
g50 - Backward search mode:
?(Nwill search backward) - Help inside less:
h
Visual mode: v (Edit current file with $EDITOR)
- Exit visual mode:
:q
5 - Summarize files
cutwc
cut
- By char:
-c- By field:
-f(a field is a tab-delimited section of a line)- Change delimiter:
-d char- Numbers: can choose a range (
cut -c 2-4)
1 | # get ether address of wlan |
wc
1 | wc 1.txt |
Search text files with regex
grep
- Find matching text within a file & print out result
- Cannot use grep to make changes
sed
Regex (basic & extended)
Quotation marks are not regex chars
^line start$line end[]match any char insideb[aei]g–>bag, beg, big-rangea[2-4]z–>a2z, a3z, a4z.any single char (except newline)a.z–>a2z, abz, aQz(and any other 3-char string that’sa.z)*appears ≥ 0 timesUse
.*for substring match+appears ≥ 1 times?0 or 1 match|multiple possible matches()group expressions\escape char
Chracter classes
predefined names
1 | [:alnum:] # alpha & numeric |
1 - grep
- Count matching lines
-c, --count- Ignore case
-i, --ignore-case- Recursive search
-r, --recursive(or: rgrep)- Extended regex
-E(or: egrep)
1 | # use char class, double brackets |
Grep AND, OR, NOT: https://www.thegeekstuff.com/2011/10/grep-or-and-not-operators/
2 - sed
Directly modifies file content from stdin & send edited file to stdout (Stream editor)
Sed operates on addresses (line numbers)
If no address: Operate on entire file
Usage
-
i\txtinsert txt to file -
c\txtreplace with provided text -
ADDRcTEXTsee usage below -
s/regex/replacesubstitute text that matches regex -
pattern/ddelete lines
1 | # modify stdin (donuts donuts) |
Slash (/) isn’t the only delimiter in sed.
You can use any character as a delimiter that’s not part of either string. (e.g. |, :)
Practice
exec: rest of command to replace current shell
Exit from program:
xtermwindow will close
Limit of pipe: based on input buffer size
Text file record: single file line that ends in newline (ASCII char LF)
A file descriptor is a number that represents process’s open files
stdout goes to the current termianl (/dev/tty)