Command Line Interface

Command Line Interface

dotfiles and materials available at @junhocho[1]

GUI보다 좋은 CUI,

CUI. Command Line Interface를 쓰시면 어디서든 쉽게, 인터넷만 있고, Terminal이나 Putty가 있으면 개발을 할 수 있다.

fit left

이런 팀뷰어 없이도 말이다.

CLI. 그래서 어떻게?

( Tmux + VIM ) 를 사용하자

right bg

CLI를 사용하는 이유.

  1. Portable (인터넷이 구리면 팀뷰어는 힘들지)
  2. Simple
  3. Automated (원하는 기능은 다 자동화 시킬 수 있다)
  4. and Cool (남들이 보면 해커인줄 알꺼야)

그리고 당신이

  • server가 있고 (노트북과 인터넷만 있으면 어딜가도 괜찮아)
  • mac이 있고 (iTerm2는 편하고 이쁘니까)
  • blogger
  • computer geek

답은 CLI.

left
드루와드루와

Coverage

  1. Ubuntu and ZSH (The OS 그리고 Shell)
  2. Vim (The editor)
  3. Tmux (The workspace)

공유할 만한 zsh, tmux, vim 설정 파일들, 클릭

SSH: Secure Shell

Secure connection to server

Host(server) IP : 147.46.89.175 (for ex)
User ID : bctjv-[yourname]
password : bctjv

Login !

  • Linux/macOS : ssh bctjv-[yourname]@147.46.89.175
  • Windows : use putty
    right fit

OpenSSH 가 서버에 설치 되어 있어야 ssh 접속 가능

sudo apt-get install openssh-server

Ubuntu (Linux)

Simple commands. 등등...

mv , cp , rm , mkdir , rmdir
ls -lh, df -lh, du -sh ./*, whoami
cp *.py /path/to/dest/
rm -rf /다/지워/버리겠다/*.txt
sudo apt-get install tmux

이런 커맨드도 있음.

cowsay
cmatrix
funny commands

left fit

Some Signals

# ==== Ex1) ====, $은 터미널에 쳐볼 것.
$ yes yell!
<C-c>   # Control - c. 돌아가고 있는 프로세스를 꺼버린다.
# ==== Ex2) ====
$ python -c '
c = 0
while True: print c; c= c+1'

<C-z>   # Control - z. 터미널상에서 잠깐 멈추고 백그라운드로!
$ fg    # 다시 아까 돌아가던 foreground로
# ==== Ex 3) ====
$ python
<C-d>   # Control - d. 아예 꺼버리기

파일 권한과 소유권

다음 상황에서

fit inline 100%

^Workspace : drwxrwxr-x : directory and has 775 permision
.zshrc : -rw-r--r-- : file and has 644 permision
hello.py : -rwxr-xr-- : file and has 754 permision

  • change permssion : $ chmod 755 hello.py : 755는 이진법으로 111 101 101, 즉 rwxr-xr-x. 숫자 세개가 각 나, 그룹, 나머지를 뜻함. 그래서 나는 rwx (읽고 쓰고 실행 권한 있음), 그룸과 나머지는 r-x (읽고 실행 권한만 있음.)
  • change ownership : $ chown userid hello.py

sudo 어떤커맨드 : borrow sudo privilege and command

추가로) 쉘 스크립트를 executable하게 바꾸기.

Write on top of shell script
#!bin/bash if shell script,
#!bin/usr/python if python script.
chmod +x script

then the script is executable as $ ./script

Do not abuse sudo 👎

^permission이 없는 것은 sudo 명령어로 해결가능.
하지만 함부로 사용 No
linux를 root 계정을 사용하는 것은 안전하지 않음.
보통 모든 유저에게 sudo 권한을 주진 않음.

Shell : 리눅스 터미널 소통 창구

  • Default shell is bash shell 그 유명한 배시쉘
  • bash shell made in 1989 which is pretty uncomfortable. 불편해

그래서 zsh을 써보자

right

Why ZSH?

  1. smart autocomplete
  2. highly customizable
  3. Bundled functions, helpers, plugin, themes : ex) git

Install zsh

# 지금은 안될 수도 있음! oh-my-zsh를 참고하자! http://ohmyz.sh
sudo apt-get install git # git 설치 ( 코드 개발 플랫폼 )
sudo apt-get install zsh # zsh 설치
cd # 홈폴도로 이동.
sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" # install
sudo chsh -s /usr/bin/zsh [your-id] # change your default shell into zsh

커스터마이즈를 해보자! git clone Junhosetting first

cd # move to home folder
git clone https://github.com/junhocho/junhosetting #Star it
cd junhosetting
vi install.txt  # peek vim

엥? vi?

특히 Vim : improved Vi. vi는 에디터. vi커맨드가 곧 vim임
Vim quit? [Alt F4] 가 아닌 다음처럼

:q 		# vim quit
:wq		# save and quit. identical to <shift-ZZ>
1 # Zsh setup
2 zsh autojump - https://github.com/wting/autojump.git
3 zsh syntax highlighting - https://github.com/zsh-users/zsh-syntax-highlighting.git
4  
5
6 #alias-tips
7 $ cd ${ZSH_CUSTOM1:-$ZSH/custom}/plugins            # 커스텀 플러그인 폴더로 이동
8 $ git clone https://github.com/djui/alias-tips.git  # 저장소를 로컬로 복사
9 $ $EDITOR ~/.zshrc                                  # 에디터로 파일을 에디터로 불러들임
10 plugins=(git ... alias-tips) 추가
11 ...

더 해보자

ZSH syntax highlight : 맞는 커맨드면 초록색, 틀린 커맨드면 빨간색

cd
# get source of zsh-syntax-highlighting
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git
# put codes in .zshrc
echo "source ${(q-)PWD}/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" >> ${ZDOTDIR:-$HOME}/.zshrc
# activate it now
source ./zsh-syntax-highlighting/zsh-syntax-highlighting.zsh

# this refreshes your .zshrc modofication to your current environment
source ~/.zshrc # dotfiles locate in home folder

It highlights if your command is valid

또 좋은 autojump : 내가 자주 가는 디렉토리로 j 커맨드로 빠르고 쉽게 이동.

some more useful commands

ls . | wc -l                        # how many files in this directory.
du -sh ./*                          # how big are folders and files in this directory
df -lh                              # list my Filesystem in human readable format
ln -s [target-folder] [make-link]   # make symbolic link
grep -nr --color "keyword-to-find" * # locate "keyword-to-find"

unzip some.zip                      # unzip
tar -xvf some.tar.gz                # untar
echo $CUDA_HOME                     # print some environment variable
wget https://goo.gl/ka7Yz5          # download file in web
wget http://www.ekn.kr/data/photos/20150938/art_1442387799.jpg # Download jpg image
python print-experiment-output.py 2>&1 | tee experiment.log # Store all print output in experiment.log
which python                        # useful to locate command

history                             # my command history
pstree                              # process tree
htop                                # system monitoring
nvidia-smi                          # gpu monitoring
who                                 # which users are online?

Alias

  • 커맨드 단축해버리기!
  • alias wn="watch nvidia-smi" 을 .zshrc에 넣어놓으면. 앞으로 wn으로 watch nvidia-smi를 빠르게 실행 가능.

You don't have time to type : grep -nr --color "keyword-to-find" *

  • put your alias at the end of .zshrc
cd
cat junhosetting/alias >> ~/.zshrc # Copy paste alias to end of .zshrc
tail ~/.zshrc # print some lines of the end of .zshrc
source ~/.zshrc # refresh this environment

grepn "key-word-to-find" * # Check the alias working

Port

Well know ports : 22 : SSH / 80 : HTTP / 3389 : Window rdp ...
Portforward from CLIENT to SERVER : ssh -L localhost:$2:localhost:$2 $1

# Ex) Do this at SERVER.
Jupyter notebook --no-browser --port 8888 # random ports 8888
# Do this at CLIENT
ssh -L localhost:8888:localhost:8888 junho@147.46.89.175
# Open web-browser in CLIENT and connect to `localhost:8888`

VNC (GUI) : Use GUI safely with SSH

SCP: Move file between client and Server

use it in CLIENT (unix) terminal.
because Client : 유동 ip / Server : 고정 ip

scp /client/A host:~/path/dest/B
# Client의 파일 A를 host의 경로 B로 옮긴다.
scp host:~/path/dest/A /client/B
# Host의 파일 A를 Client의 B로 옮긴다.
scp -r junho@147.46.89.175:~/Downloads/WordCount ~/Workspace/
# -r 은 재귀적으로. 서버의 WordCount 디렉토리와 안의
# 모든 파일을 내 client의 Workspace의 복사

Windows는 WinSCP

fit right

Killing Process

$ python -c '
c = 0
while True: print c; c= c+1'

<C-z> # go to sleep and background.
$ ps aux | grep python # print process that contains `python`

inline

kill -9 [process-id] : 356 in this case

process killed!

2. Vim

유명한 IDE들,
bg
Visua Studio , Eclipse, Webstorm, Android studio, Pycharm, ZeroBaneStudio는 좋지만 client일때 좋음. server에서 사용하기는 힘들다.

SSH에서는 VIM만큼 편한게 없다!

Vim

  • Vim : improved Vi.
  • probably already installed in your system
  • Highly customizable
  • setting file : .vimrc

Modal editing

  • Normal - navigate the structure of the file <esc>
  • Insert - editing the file i, o, a, s, ...
  • Visual - highlight portions of the file to manipulate at once v, shift-v, ctrl-v
  • Ex - command mode :, /, ?

vim에서 마우스는 사용할 필요가 없다.

h j k l

⬅️ ⬇️ ⬆️ ➡️

12j : move down 12 tiems, numbers affect

  • :29 : move to line 29
  • :set number : show line numbers
  • :set nonumber : no usually the opposite of command

그외에

  • ^e - scroll the window down
  • ^y - scroll the window up
  • ^f - scroll down one page
  • ^b - scroll up one page
  • H - move cursor to the top of the window
  • M - move cursor to the middle of the window
  • L - move cursor to the bottom of the window
  • zz : move window so that my cursor is at center
  • u : undo
  • ^r : redo
  • :w : save
  • :q : quit
  • :wq : save and quit
  • gg - go to top of file
  • G - go to bottom of file


vim의 learning curve.... 입문부터 고수까지 빡셈... 하지만 익숙하면 너무 편하다.

다음의 중요한 3 요소

text objects

  • w - words
  • s - sentences
  • p - paragraphs

Motions

  • a- all
  • i - in
  • t - 'til
  • f - find forward
  • F - find backward

Commands

  • d - delete (also cut)
  • c - change (delete, then place in insert mode)
  • y - yank (copy)
  • v - visually select

이것들로

{command}{text object or motion} 조합으로 아주 편리하게 사용가능하다.

diw : delete in word

caw : change all word

yi) : yank all text inside parentheses

va" : visually select all inside doublequotes including doublequotes

방금 한 커맨드 또 하는 건 The DOT command .로 된다.

Additional commands

  • dd / yy - delete/yank the current line
  • D / C - delete/change until end of line
  • ^ / $ - move to the beginning/end of line
  • I / A - move to the beginning/end of line and insert
  • o / O - insert new line above/below current line and insert
  • J - delete line break. pretty useful
  • p - paste
  • * on word - find all this words.
  • ^a on number - increment

근데 vim의 포텐에는 끝이 없다: Macro

A sequence of commands recorded to a register

Record a macro

  • q{register}
  • (do the things)
  • q

Play a macro

  • @{register}

텍스트에서 지금 커서의 위치를 marking해놓고 돌아오는게 가능

  • mk : mark position at k
 `k : move cursor to position k

Ex mode에서 가능한 편리한 커맨드들

  • /someword : find someword
  • :spl / :vspl : split (horizontal or vertical) vim pane
  • ^w + w/arrow : move pane in vim
  • :e. : file tree
  • :%s/foo/bar/g : replace all foo to bar

: 로 시작하는 것들은 vimrc에서 초기 명령어로도 사용 가능.

  • :syntax on : syntax on
  • :set paste : paste mode. Useful when using vim indent option
  • :set cursorline : show cursor with underline

vimrc는 vim의 세팅 파일.

cp ~/junhosetting/vimrc ~/.vimrc

Plugins : install what you need. vim 편리의 끝판왕

Vim은 엄청나게 customizable하다.

original

Not an IDE. It's VIM

Install Vundle with plugins

cd
git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim
# clone in ~/.vim/bundle/ and setup your vimrc with plugins
vi # then do :PluginInstall
# Test :NERDTree with <F2> in vim
# Test if autocomplete works

right 80%

ctags : Source code inspection

sudo apt-get install ctags
cd your-project
ctags -R . # will produce `tags` in the folder
vi code.cpp
< C - t > # to go inside declration
< C - ] > # to go back

3. Tmux : Terminal Multiplexer

vim + tmux

Why Tmux?

  • Don't want to stop your SSH session.
    1. Experiment session
    2. Downloading big file
    3. web-server
  • Extendable Workspace
  • And Maintain your session
  • Co-operation
tmux new -s [session-name]	  # create new session
tmux ls                       # list existing session
tmux attch -t [session-name]	# attach existing session

tmux new -s py-practice
<C-b> : Tmux binding-key.

  • will change it to <C-a> unless you have flexible finger bone

<C-b> c , bind c : New window
bind d : dettach from working session

Let's configure Tmux.

cp ~/junhosetting/tmux.conf ~/.tmux.conf  #  dotfile로 이름바꿔서 복붙
tmux source .tmux.conf    # If you have working tmux session
# Now your Tmux looks better and <C-a> is the binding-key

tmux new -s [session-name]

bind c : new window
bind n : Next window
bind p : Previous window
bind % : vertical split pane
bind " : horizontal split pane
bind h(jkl, arrow) : move my cursor pane to pane
bind [ : copy-mode / q : copy-mode exit
exit / <C-d> : quit pane

Synchronize-panes

bind :setw synchronize-panes

fit

화면 쪼개기!

bind % and bind "

fit

결론

답은 linux + GIT + tmux + vim

참고할만한 dotfiles들

dotfiles and materials available at @junhocho[1:1]


  1. Inspired from @nicknisi ↩︎ ↩︎