Linux Basic Configuration and Operation (2)

Some people have told me they don't think a fat penguin really embodies the grace of Linux, which just tells me they have never seen a angry penguin charging at them in excess of 100 mph.
                                     —— Linus Torvalds

linux.png

This blog is written for Debian/Ubuntu, and it is not suit to other Linux distribution, such as Fedora/CentOS.

Text Editor - Vim

Install

Install vim by apt.

1
$ sudo apt install vim

Set some basic configuration for vim by modifying '~/.vimrc'.

1
$ vi ~/.vimrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
set tabstop=4
set shiftwidth=4
set expandtab
set smarttab
set showcmd
set number
set showmatch
set hlsearch
set incsearch
set ignorecase
set smartcase
set backspace=2
set autoindent
set textwidth=120
set formatoptions=c,q,r,t
set ruler
set mouse=a
syntax on

About 'Tab', choose one from the following two method depending a specific situation, such as editing Makefile.

  • Replace 'Tab' with 4 spaces.
1
set expandtab
  • Change length of 'Tab' to length of 4 spaces.
1
set noexpandtab

Usage

Edit a text file by vim.

1
$ vim <filename>

Press Esc to start General Mode.

Operation Description
Type u roll back operation
Type Ctrl-R roll forward operation
Type Ctrl-F move forward page
Type Ctrl-B move back page
Type Ctrl-U move up view
Type Ctrl-D move down view
Type <n>x cut(delete) n characters from position of cursor
Type <n>dd cut(delete) n line from line of cursor
Type <n>yy copy n line from line of cursor
Type p paste to the back of cursor
Type r replace character in position of cursor
Type Shift + Cursor select multiple lines
Type Ctrl-Shift + Cursor select rectangle area
Type Ctrl-W + < decline width of current window
Type Ctrl-W + > increase width of current window
Type Ctrl-W + - decline height of current window
Type Ctrl-W + + increase height of current window
Type : start Command Mode
Type Ctrl-V start Visual Block Mode

Press : in General Mode to start Command Mode.

1
2
3
4
5
6
7
8
9
:wq                     # save and quit
:q! # no save and force to quit
:set nu # show lines numner
:<m>,<n>d # cut(delete) m to n lines
:<m>,<n>y # copy m to n lines
:s/<str1>/<str2>/g # replace str_1 with str_2 in current line
:%s/<str1>/<str2>/g # replace str_1 with str_2 in every line
:vs [<filename>] # horizontal split screen to edit file
:sv [<filename>] # vertical split screen to edit file

Press Ctrl + V in General Mode to start Visual Block Mode.

It important that make sure your position of cursor is suitable before starting Visual Block Mode.

  • Multi-line comment
    • choosing code by Press Up or Down.
    • press I before typing // or #.
    • pressing Esc again is necessary.
  • Cancel multi-line comment
    • choosing code by Press Up or Down.
    • press Left or Right to include // or #.
    • pressing d.

Template

Make some file as template file.

1
2
3
4
$ mkdir ~/.vim/template/
$ cd ~/.vim/template/
$ ls
template.c template.cxx template.cpp

Add the following code to ~/.vimrc.

1
2
3
autocmd BufNewFile *.c 0r ~/.vim/template/template.c        
autocmd BufNewFile *.cpp 0r ~/.vim/template/template.cpp
autocmd BufNewFile *.cxx 0r ~/.vim/template/template.cxx

NERDTree

The NERD tree allows you to explore your filesystem and to open files and
directories.

1
2
$ mkdir -p ~/.vim/autoload ~/.vim/bundle && curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim
$ git clone https://github.com/scrooloose/nerdtree.git ~/.vim/bundle/nerdtree

Add the following code to ~/.vimrc.

1
2
3
4
5
6
7
8
9
10
execute pathogen#infect()
filetype plugin indent on
map <F2> :NERDTreeToggle<CR>
let g:NERDTreeDirArrowExpandable = '+'
let g:NERDTreeDirArrowCollapsible = '-'
let g:NERDTreeWinPos='left'
let g:NERDTreeSize=30
let g:NERDTreeShowLineNumbers=0
let g:NERDTreeHidden=0
autocmd vimenter * if !argc() | NERDTree | endif

Press F2 to switch the tree directory.
Press r to refresh the tree directory.

CLick this link, see more detailed info about ~/.vimrc or download template file instead of re-editing.

Command Prompt

For User

View configuration of bash.

1
$ vim + ~/.bashrc

Add the following text in the last line of file ~/.bashrc.

1
PS1="\[\e[32;1m\][\[\e[32;1m\]\u\[\e[31;1m\]@\[\e[32;1m\]\h\[\e[37;1m\]: \[\e[34;1m\]\w\[\e[32;1m\]]\[\e[37;1m\]\\$ \[\e[0m\]"

Reload configuration.

1
$ . ~/.bashrc

For Root

View configuration of bash.

1
2
$ su root
# vim + ~/.bashrc

Add the following text in the last line of file ~/.bashrc.

1
PS1="\[\e[32;1m\][\[\e[32;1m\]\u\[\e[31;1m\]@\[\e[32;1m\]\h\[\e[37;1m\]: \[\e[34;1m\]\w\[\e[32;1m\]]\[\e[37;1m\]\\$ \[\e[0m\]"

Reload configuration.

1
# . ~/.bashrc

Result

cmd_prompt.png

Terminal Manager - Tmux

Install

Install tmux by apt.

1
$ sudo apt install tmux

Modify configuration file '~/.tmux.conf'.

1
$ vim ~/.tmux.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bind r source-file ~/.tmux.conf
set -g prefix C-a
unbind C-b
set -g mouse on
set -g renumber-windows on
set-window-option -g mode-keys vi
set -g message-fg green
set -g message-bg black
set -g message-attr bright
set -g status-interval 1
set -g status-justify left
set -g status-left-length 20
set -g status-right-length 50
set -g status-bg '#333333'
set -g status-fg '#ffffff'
set -g status-left '#[fg=#031dab, bg=#55bb00] S[#S] #[fg=#031dab,bg=#009c00]W[#I] #[fg=#031dab,bg=#007700]P[#P] '
set -g status-right '#[fg=#031dab,bg=#55bb00] [#h] #[fg=#031dab,bg=#009c00] %Y-%m-%d #[fg=#031dab,bg=#007700] %H:%M:%S '
set -g status-justify centre
setw -g window-status-current-format '#[bg=#ff0000, fg=#ffffff, bold] W[#I] #W '
setw -g window-status-format '#[bg=#0000ff, fg=#ffffff] W[#I] #W '
setw -g monitor-activity on
set -g visual-activity on

CLick this link, see more detailed info about ~/.tmux.conf or download it instead of re-editing.

Usage

It's necessary to manually load the configuration file for the first time.

In the Tmux shell, typing Ctrl-B and editing source-file ~/.tmux.conf

New session and window by using tmux.

1
$ tmux [new -s <SessionName> -n <WindowName>]

The following hot key is important.

Operation Description
Type Ctrl-A + r reload configuration
Type Ctrl-A + " horizontal division window
Type Ctrl-A + % vertical division window
Type Ctrl-A + c create a new window
Type Ctrl-A + , rename current window
Type Ctrl-A + & delete current window
Type Ctrl-A + <num> go to the num-th window
Type Ctrl-A + n go to next window
Type Ctrl-A + p go to previous window
Type Ctrl-A + d detach current session
Type Shift + Cursor select multiple lines
Type Ctrl-Shift + Cursor select rectangle area

It is suggested that using tmux create a new session with a session name, like this:

1
$ tmux new -s <session_name>

After detach one session by using Ctrl-A + d, you can see currently existing all the sessions.

1
2
3
$ tmux ls
session_name_1: 1 windows (created Thu Dec 12 18:05:28 2019) [118x105]
session_name_2: 1 windows (created Thu Dec 12 19:08:29 2019) [118x105]

Attach one existing session again by the following command:

1
$ tmux a -t <session_name>

Compiler - GCC

Install

1
$ sudo apt install gcc

Usage

1
2
3
4
5
6
7
$ tree
.
├── func1.c
├── func1.h
├── func2.c
├── func2.h
└── main.c

The simple command is gcc main.c fun1.c fun2.c -o execute, and the following steps show more detailed command.

Pretreatment

The step contains of removing comment, replacing macro, including head files and adding line numbers.

1
2
3
$ gcc -E main.c -o main.i
$ gcc -E func1.c -o func1.i
$ gcc -E func2.c -o func2.i

Compilte

The step contains of analysing lexical, analysing grammar, analysing semantic and generating assembly code.

1
2
3
$ gcc -s main.i -o main.s
$ gcc -s func1.i -o func1.s
$ gcc -s func2.i -o func2.s

Assembler

The assembler will convert assembly code to machine code.

1
2
3
$ gcc -c main.s -o main.o
$ gcc -c func1.s -o func1.o
$ gcc -c func2.s -o func2.o

It contains of linking target file and generate executable file.

1
$ gcc main.o fun1.o fun2.o -o execute

Another way of linking is to static link some libraries (.a file in Linux and .lib file in Windows) if they exists, if not you should make some libraries by yourself.

The command is gcc [options] [source files] [object files] [-Ldir] -llibname [-o outfile]. See more.

1
2
3
4
5
6
$ mkdir lib/
$ ar rcs lib/libfunc.a func1.o func2.o
$ ar -t lib/libfunc.a
func1.o
func2.o
$ gcc main.o -Llib/ -lfunc -o execute

The bset way of linking is to dynamic Link some shared libraries (.so file in Linux and .dll file in Windows) if they exists, if not you also could make your shared libraries. See more

Degugger - GDB

Install

1
$ sudo apt install gdb

Usage

You should use GCC or Clang with the important parameter -g before using GDB.

1
2
$ gcc main.o -Llib/ -lfunc -o execute -g 
$ gdb -q execute

Basic Command

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
:b <linenum>                                # equals `break`
:set args {<argv[1]> | <argv[2]> | ...} # set agguments
:show args # show arguments
:r # equals `run`
:n # equals `next`
:s # equals `step`
:f # equals `finish`
:p # equals `print`
:h {...} # show help info
:dispaly {<var> | <exp>} # show value
:i {...} # equals `info {...}`
:c # equals `continue`
:u [<linenum>] # equals `until`
:whatis <var> # show type
:watch {<var> | <exp>} # monitor sth until its value changed
:d # delete all the breakpoints
:d [<pointnum>] # delete the special one by number
:clear <linenum> # clear breakpoint in one line
:q # equals `quit`

Breakpoint Mark

  • B : Program has run the breakpoint at least once.

  • b : Program has not run the breakpoint.

  • H : Program has run the hardware breakpoint at least once.

  • h : Program has not run the hardware breakpoint.

  • + : The breakpoint is active.

  • - : The breakpoint is inactive.

Use GDBTUI

For programer, the TUI is more comfortable than CLI while debugging program.

1
2
3
$ gdbtui -q execute
$ tty
/dev/pts/4

Some useful command in GDBTUI.

1
2
3
4
5
:h layout                       # show help info of layout
:layout src
:layout asm
:layout split
:layout regs

Press Ctrl + L to refresh the TUI.

Redefine IDE

Vim + Tmux + GCC + GDBTUI = IDE

ide_linux.png

Shell Script

Edit Makefile

The Grammar of Makefile is:

1
2
3
4
5
6
7
8
9
target_1 ... : prerequisites ...
command
...
...
target_2 ... : prerequisites ...
command
...
...
... ... ...

Link and compile multiple files.

1
2
3
$ ls
declare.h implement.cpp main.cpp show.cpp
$ vim Makefile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
all: lexAnalyze show clean_o

lexAnalyze: main.o implement.o
g++ main.o implement.o -o lexAnalyze

main.o: main.cpp
g++ -c main.cpp -o main.o

implement.o: implement.cpp
g++ -c implement.cpp -o implement.o

show: show.o implement.o
g++ show.o implement.o -o show

show.o: show.cpp
g++ -c show.cpp -o show.o

clean_o:
rm -f *.o

When editing Makefile, 'Tab' is necessary, which cannot be replace with 4 spaces.

1
2
3
4
5
6
7
8
9
10
$ make
g++ -c main.cpp -o main.o
g++ -c implement.cpp -o implement.o
g++ main.o implement.o -o lexAnalyze
g++ -c show.cpp -o show.o
g++ show.o implement.o -o show
rm -f *.o
$ ls
declare.h implement.cpp main
main.cpp show show.cpp

Batch Replace

Type the following command in terrminal.

1
$ sed -i "s/OldString/NewString/g" `grep OldString -rl FileDir`

Replace 'shendu' with 'depth', if 'shendu' in .cpp file of current directory.

1
$ vim Makefile

1
2
replace:
sed -i "s/shendu/depth/g" `grep shendu -rl *.cpp`
1
$ make replace

Boot Repair

Problem

GNU GRUB meet a problem so that cannot boot os normally, such as show the following code.

1
2
3
4
error: incompatible license.
error: incompatible license.

Press any key to continue..._

Or like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
error: syntax error. 
error: Incorrect command.
error: syntax error.
error: syntax error.
error: Incorrect command.
error: syntax error.
error: syntax error.
error: Incorrect command.
error: syntax error.
error: can't find command `recordfail'.
error: can't find command `load_video'.

Press any key to continue..._

Solution

Most of time, you need install and usool called 'boot-repair' without access to os (sometimes you are allowed to access). As me, a simple but useful way is to use usb that has been as a start disk.

  1. Set BIOS and boot by usb.

  2. Make sure the net connection is ok.

  3. Copy and paste the following code to shell.

1
2
3
4
$ sudo apt install software-properties-common; \
sudo add-apt-repository -y ppa:yannubuntu/boot-repair; \
sudo apt-get update; \
sudo apt-get install -y boot-repair && boot-repair
  1. Start to repair and wait a moment (if prompt appears, try do as what it show).

boot-repair.png

  1. Reboot by GNU GRUB2 instead of usb.

Reference


Unfinished