본문 바로가기
Development

Ubuntu 다양한 CLI/bash script 사용 법

by IMCOMKING 2016. 8. 22.

## Bash script 튜토리얼

https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php#ifelse

 

# Ubuntu 파일 경로 의미
/bin:  core tools, some admin tools, contents controlled by package manager.
/usr/bin: mostly end user tools, contents controlled by package manager as well.
/usr/local/bin: yours to use and abuse.



# Wildcard의 모든 subdirectory 인식

shopt -s globstar       (.bashrc에 추가해주면 편하다.)

ls data/**/*.json

 

https://unix.stackexchange.com/questions/60255/what-is-wild-card-to-select-all-directories-in-a-directory

 

# Vim에서 키워드 검색

/검색할키워드
엔터

 

# Shell에서 입력했던 명령어 보기
history

 

# Bash 에서 *와 **의 의미
* 하위 모든 파일
** 하위 모든 파일(하위 디렉토리포함. 즉 recursive)

 

# SSH로 자기자신에 한 번 더 들어가는 듯한 효과의 명령어: 

script /dev/null

또한 이 명령어는 screen이 버그스럽게 작동할 때 사용해줘도, screen의 버그를 해결할 수가 있음.

 

# su: 스위치 유저

 

# Ubuntu Version 확인
lsb_release -a

 

# Alias 사용하기
자주쓰는 약어 등을 간편하게 등록하는 기능이 바로 alias이다.

아래와 같이 다양한 방식으로 alias를 쓸 수 있다.

alias lsd='ls -l | grep "^d"' 

alias rpmdesc='rpm -qa --queryformat "% : %\n"'

또한 해제하기 위해서는 unalias를 사용하면된다.

그냥 alias만 치면 list를 볼 수 있다.

 

http://webdir.tistory.com/107

 

 

# 로그인 루프

http://askubuntu.com/questions/223501/ubuntu-gets-stuck-in-a-login-loop

 

# USB 사용법

fdisk -l

mount -t vfat /dev/sdc1 /media/usb

#주의. 반드시 sdc1이라고해야함

http://egloos.zum.com/jinrowin/v/1369342

http://vulpecula.tistory.com/24

 

# 우분투 복구모드(Grub)

Shift키 누르면서 부팅하면, 복구모드로 진입함

 

# 특정 폴더를 제외하고 전부 복사하기

rsync -av --exclude= source dest

http://stackoverflow.com/questions/2193584/copy-folder-recursively-excluding-some-folders

 

## rsync 기본 사용법

rsync -avz test_file.py user@10.*.*.*:/home/

 

https://www.lesstif.com/system-admin/rsync-data-backup-12943658.html#:~:text=%EB%8F%99%EA%B8%B0%ED%99%94%EC%8B%9C%20%EB%AA%A9%EC%A0%81%EC%A7%80(destination)%20%ED%8C%8C%EC%9D%BC,conf%20%EB%A1%9C%20%EB%8D%AE%EC%96%B4%EC%8D%A8%20%EB%B2%84%EB%A6%B0%EB%8B%A4. 

 

 

# 컴퓨터끄기

 

sudo poweroff now

 

 

- 단축키들

ctrl + alt + t : 새로운 terminal 창 생성
ctrl + shift + t : 새로운 terminal Tab 생성

ctrl + shift + q : terminal 창 닫기
ctrl + shift + w / ctrl + d / exit 입력 : terminal Tab 닫기

ctrl + page UP/DOWN : terminal Tab 이동

ctrl + '+' : terminal 크기 확대
ctrl + '-' : terminal 크기 축소

ctrl + q : 아무 창 닫기

 

 

- 새로 설치한 HDD mount 하기
http://www.whatwant.com/686

위의 방법보다, GUI를 이용해서 하면 매우 쉽게 가능함.

HDD를 컴퓨터에 설치하고 실행
좌상단의 검색창을 켜서 Disks 프로그램을 실행
Volumes에서 Free Space라고 되어있는 새로 설치한 HDD를 선택
우측상단의 설정버튼에서 Format을 선택
적절한 옵션(그냥 default 사용하면 될 듯)을 고르고 포멧을 시킴
+ 버튼을 누르고 파티션을 생성(hdd2와 같은 이름 지정)
플레이 버튼을 눌러서 Mount 시킴 --> /media/~~ 에 들어가면 해당 하드디스크가 생김


 

 

- 특정 유저의 process 검색
ps -u [username]
ps -efl | grep [username]

 

 

- super유저로 바꾸기 
sudo su 

- cd에서의 수도권한 필요시 
sudo -s 

 

 

- user의 home dir바꾸기

usermod -m -d /newhome/username username

* 이때 -m 을 추가하면, 기존에 쓰던 home_dir의 contents를 모두 옮긴다는 뜻이다.

https://stackoverflow.com/questions/20797819/command-to-change-the-default-home-directory-of-a-user

 

위 명령어를 입력했는데

"usermod: user502 is currently used by process 4220"

이런 에러가 뜬다면, 해당 process를 전부 kill하고 실행하면 된다.

https://stackoverflow.com/questions/28972503/linux-usermod-user-is-currently-used-by-process

 

* usermod -d로 home_dir을 바꾸고 난 다음에는 반드시 .bashrc와 .profile을 복사해와야한다.

 

 

 

- 디렉토리, 파일 용량확인
df -h

du -h -d 1 .

du -sh *

 

du -h --max-depth=1 /path/to/folde

https://opensource.com/article/18/7/how-check-free-disk-space-linux

 

- 직전 실행문에 수도권한 부여
sudo !! 

 

- bash 에서 for loop 사용하기:

echo "Bash version $}..."
for i in
do
    echo "$th iteration"
    python main.py >> irl.out
    # > : write / >> append
done

https://www.cyberciti.biz/faq/bash-for-loop/

- bash 에서 해당 폴더의 파일 리스트 가져오기 :

find /my/sourcedir/ -type f -maxdepth 1

 

- 이전 디렉토리로 가기(cd prev)

cd -

 

 

- 앞에서 실행한 결과를 한줄씩 가져와서 실행하기 : (command per line)

... | xargs -n1 command
... | while read -r line; do command "$line"; done

http://unix.stackexchange.com/questions/7558/execute-a-command-once-per-line-of-piped-input

 

- bash 에서 앞에서 가져온 대상을 인자로 받아서 특수한 명령 수행하기 :

~~~ | xargs -0 cp -t /my/destination

 

ex) bag이란 이름이 들어간 파일을 검색한 다음, do ~~부분의 실행을 하고 .csv로 바꾸어서 저장하기

find . -type f -maxdepth 2 | grep bag | while read -r line; do rostopic echo -b "$line" -p /tf > "$"csv; done~~~ | xargs -0 cp -t /my/destination
 

 

http://stackoverflow.com/questions/7265272/how-to-list-files-in-directory-using-bash

 

- bash 문자열에서 확장자 부분을 삭제하는 방법:

filename = "$"

$변수명은 bash에서 특정한 변수에 접근할 때 사용하는 문법 규칙

http://stackoverflow.com/questions/965053/extract-filename-and-extension-in-bash

 

- bash 문자열 삭제

"$" : 앞에서 문자열 삭제
"$" : 뒤에서 문자열 삭제

https://wiki.kldp.org/HOWTO/html/Adv-Bash-Scr-HOWTO/string-manipulation.html

 
- 중간 변수를 사용하여 문자열을 2번 수정하기
find -name "*.csv" | while read -r line; do line2="$"; cp $line csv_files/"$"; done
 
>while 문 안에서도 ; 를 계속 입력하면 여러줄을 수행할 수 있음
>그리고 / 은 \/ 의 형태로 입력이 가능함.
 
- sed를 사용하여 줄단위 조작
 
sed -i : in-place 파일 자체에서 수정하기
 

 

- 출력되는 줄 수 카운트 하기

ls | wc -l

 

 

- shell scrip상에서 string으로 덧셈 뺄셈하기

$(( $(ls | wc -l)-$(2) ))

https://stackoverflow.com/questions/8875151/subtracting-strings-that-are-numbers-in-a-shell-script

 

 

- 특정한 내용의 string을 담고 있는 파일 검색하기

grep -r <찾을str> *

 

댓글