일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
- Podman
- 맛집
- DSEC
- 10km
- Grafana
- docker
- 중식
- 2021
- Kubernetes
- 한강
- 러닝
- 건대입구역
- Linux
- 소모임
- 대구
- 하체
- Python
- 오답노트
- 정보처리기사
- 자전거
- 달리기
- GitHub
- zabbix
- 뚝섬유원지
- Run The Bridge
- Shell
- 성수대교
- 대전
- 유산소
- 힐링
- Today
- Total
Run The Bridge
shell script master -8- 본문
0. 커맨드라인포토샵(imagemagick)
pass
1. 명령어(nohup)
터미널에서 실행하는 명령어를 백그라운드화 시켜본다.
sleep 1000 # 해당 명령어를 사용하면 프롬프트에 어떤 활동도 할 수 없다.
---
로그아웃이나 터미널 종료 이후에도 명령이 데몬(daemon)화되어 계속 실행할 수 있게 도와주는 명령어(nohup)
nohup
---
date;nohup ./mydaemon.sh 1>/dev/null 2>&1 0</dev/null &
Mon Feb 7 00:36:16 KST 2022
[1] 94209
1>/dev/null: 표준 출력은 휴지통으로 들어간다.
2>&1: 표준 오류는 표준 출력으로 제어된다.
0</dev/null: 표준 입력을 차단
&: 백그라운드 프로세스화
---
mydaemon.sh 내용은 다음과 같다.
#!/bin/bash
for i in {1..60};do
date >> mydaemon.log
sleep 1
done
2. 명령어(md5sum)
간단한 hello world 메시지를 찍어내는 c파일을 작성한다.
cat helloworld.c
#include <stdio.h>
int main() {
printf("hello world by C\n");
return 0;
}
---
gcc 옵션을 통해 컴파일하고, helloworld를 실행시켜본다.
gcc -o helloworld helloworld.c
./helloworld
hello world by C
---
설치스크립트로 만들기 위해 tar로 변환한다.
tar cf helloworld.tar helloworld
---
md5로 무결성체크를 한다.
md5sum helloworld.tar
af76305a14e989ececd1c71170a9c0a8 helloworld.tar
---
강사님이 만들어준 .sh파일에 md5부분을 위에서 나온 md5값으로 바꿔준다.
#!/bin/bash
# Copyright (c) 2015 guileschool.com
# All rights reserved.
#
# NAME: helloworld.sh
# VER: 1.0.0
# PLAT: linux
# DESCR: tutorial of md5sum
# BYTES: 222326344
# LINES: 48
# MD5: af76305a14e989ececd1c71170a9c0a8
# NOTE: inspired by Anaconda2-2.4.1-MacOSX-x86_64.sh
THIS_DIR=$(cd $(dirname $0); pwd)
THIS_FILE=$(basename $0)
THIS_PATH="$THIS_DIR/$THIS_FILE"
PREFIX=$THIS_DIR #$HOME/anaconda2
BATCH=0
FORCE=0
# verify the MD5 sum of the tarball appended to this header
MD5=$(tail -n +48 "$THIS_PATH" | md5sum)
echo $MD5 | grep af76305a14e989ececd1c71170a9c0a8 >/dev/null
if (( $? )); then
echo "WARNING: md5sum mismatch of tar archive
expected: af76305a14e989ececd1c71170a9c0a8
got: $MD5" >&2
fi
# extract the tarball appended to this header, this creates the *.tar.bz2 files
# for all the packages which get installed below
# NOTE:
# When extracting as root, tar will by default restore ownership of
# extracted files, unless --no-same-owner is used, which will give
# ownership to root himself.
cd $PREFIX
tail -n +48 "$THIS_PATH" | tar xf - --no-same-owner
if (( $? )); then
echo "ERROR: could not extract tar starting at line 48" >&2
exit 1
fi
${THIS_DIR}/helloworld
exit 0
---
그 후 md5sum.sh 파일과 helloworld.tar파일을 하나로 합쳐준다.
cat helloworld_md5sum.sh helloworld.tar > helloworld.sh
우리는 이러한 파일을 설치 스크립트라고 부른다.
---
위와 같은 내용은 스크립트를 통한 프로그램 제작 및 배포할 때 보안적으로 유용하게 사용이 가능하다.
3. 명령어(tee)
우리가 입력한 명령이 제대로 들어갔는지 확인하면 좋겠는데? 라고 생각할 수 있다.
그러면 리눅스에서 제공하는 'tee'라는 명령어를 사용해보자.
'tee'라는 명령을 통해 표준출력을 프롬프트에 뿌릴 수 있다.
echo "Jurassic World" | tee steven.txt #overwrite
Jurassic World
---
실제로 steven.txt 파일에 값이 담겨있다.
cat steven.txt
Jurassic World
---
그러면 할때마다 overwirte되면 어쩌지? 할 수 있는데, '-a' 옵션을 줘서 append 시킬 수 있다.
echo "Jurassic World" | tee -a steven.txt # append
cat steven.txt
Jurassic World
Jurassic World
---
또한 표준에러의 출력도 할 수 있다.
grep -i "Star Wars" steven.txt lucas.txt 2>&1 | tee george.txt # error
grep: lucas.txt: No such file or directory
cat george.txt
grep: lucas.txt: No such file or directory
4. 히어독(HEREDOC)
ssh -p 22 "당신의 다른 VM" << 'HERE'
> uname -r
> exit
> HERE
VM을 한 대 더 만들어서 하면 실습에 용이해보인다.
나는 다음과 같이 사용하였다.
172번 vm에 접속하자마자 ssh키를 묻고, uname -r로 커널버전을 출력하고 곧바로 exit 하였다.
ssh -p 22 192.168.200.172 << 'HERE'
> uname -r
> exit
> HERE
Pseudo-terminal will not be allocated because stdin is not a terminal.
The authenticity of host '192.168.200.172 (192.168.200.172)' can't be established.
ECDSA key fingerprint is SHA256:2mgNC0vT5fKsNS1KGiw8n5NOxZqPrr5vWHJNADkmMto.
ECDSA key fingerprint is MD5:f2:59:77:51:bb:d9:21:bd:67:66:99:d0:e7:b4:64:f4.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.200.172' (ECDSA) to the list of known hosts.
root@192.168.200.172's password:
3.10.0-1160.49.1.el7.x86_64
---
HERE부분에 인용부호("")를 뺴고 입력해본다.
출력값을 보면, ssh로 로그인하기 전에 경로인것을 알 수 있다.
pwd
/root/shell_script/shell_cmd
ssh -p 22 root@192.168.200.172 <<HERE
> echo PWD is ${PWD}
> exit
> HERE
Pseudo-terminal will not be allocated because stdin is not a terminal.
root@192.168.200.172's password:
PWD is /root/shell_script/shell_cmd
---
이제 인용부호를 넣고 다시 실행한다.
앞선 실행결과와 다르게, ssh 접속연결을 하고 난 후 pwd을 출력하는 것을 알 수 있다.
ssh -p 22 root@192.168.200.172 << 'HERE'
> echo PWD is ${PWD}
> exit
> HERE
Pseudo-terminal will not be allocated because stdin is not a terminal.
root@192.168.200.172's password:
PWD is /root
이유: HEREDOC 문서에 따르면 인용부호가 사용된 내부에 사용된 환경변수를 확장이 일어난 시점을 다르게 처리한다.
인용부호가 사용된 히어독은 'echo PWD is ${PWD}'의 명령을 ssh가 사용된 이후로 넘긴다.
그래서 로그인 이후에 환경변수 확장이 일어난다.
히어독은 원격 서버 시스템에 어떤 자료 데이터를 생성 후, 로그아웃할 때 매우 유용하게 활용할 수 있을 것으로 보임
---
다음과 같이 해당 결과 값을 log에 담고 싶을 때, 리다이렉션 기호 '>'를 사용해준다.
ssh -p 22 root@192.168.200.172 <<'HERE' > log
> echo PWD is ${PWD}
> exit
> HERE
Pseudo-terminal will not be allocated because stdin is not a terminal.
root@192.168.200.172's password:
root@kube-master ~/shell_script/shell_cmd #
root@kube-master ~/shell_script/shell_cmd # cat log
PWD is /root
추가로 히어독 이름이 HERE일 필요는 없다.
사용자 정의 설정이다. 원하는 이름으로하자
5. 사례분석(HEREDOC을 활용)
간단한 함수를 하나 만든다.
여기서 히어독을 사용해서 출력을 한다.
usage() {
> cat <<HEREDOC
> Installs Anaconda2 2.4.1
>
> -b run install in batch mode (without manual intervention),
> it is expected the license terms are agreed upon
> -f no error if install prefix already exists
> -h print this help message and exit
> -p PREFIX install prefix, defaults to
> HEREDOC
> }
usage() {
cat <<HEREDOC
Installs Anaconda2 2.4.1
-b run install in batch mode (without manual intervention),
it is expected the license terms are agreed upon
-f no error if install prefix already exists
-h print this help message and exit
-p PREFIX install prefix, defaults to
HEREDOC
}
---
그러면 이제 usage를 입력하면?
이렇게 메뉴얼을 알려주는 명령어로 재탄생하게 된다.
usage
Installs Anaconda2 2.4.1
-b run install in batch mode (without manual intervention),
it is expected the license terms are agreed upon
-f no error if install prefix already exists
-h print this help message and exit
-p PREFIX install prefix, defaults to
6. 히어스트링
히어독처럼 히어스트링이라는 것도 있다. '<<<' 를 써주면 된다.
sed 's/hello/goodbye/' <<< 'hello world'
goodbye world
그러면 출력이 hello 값이 goodbye로 바뀌는 것을 알 수 있다.
---
IFS 함수를 써서 ','로 분리시켜준 단어들을 read 명령어를 통해 c1 c2 c3 c4로 넘긴다.
IFS=$',' read -r c1 c2 c3 c4 <<< "france, russia,UK,austria"
printf "%s %s %s %s\n" "$c4" "$c3" "$c2" "$c1"
austria UK russia france
7. 명령어(uniq)
다음과 같은 과일 목록이 저장된 파일이 있다.
파일 이름을 보면 동일한 단어가 중복되어 있다.
cat fruits_multi.txt
apple
apple
apple
apple
strawberry
strawberry
orange
---
uniq 명령을 쓰면, 반복된 단어를 정리해서 하나의 단어로 출력시켜 준다.
uniq fruits_multi.txt
apple
strawberry
orange
---
해당 단어가 몇 번 반복되는지 출력가능
uniq -c fruits_multi.txt
4 apple
2 strawberry
1 orange
---
반복이 일어나는 단어의 출력도 가능하다.
uniq -d fruits_multi.txt
apple
strawberry
---
uniq -c: 몇 번 반복되는지 출력
uniq -d: 반복이 일어나는 단어 출력
8. 명령어(sort)
cat fruits.txt
grapes
orange
tomato
strawberry
apple
---
sort 명령어를 통해 알파벳 순서대로 정렬할 수 있다.
sort fruits.txt
apple
grapes
orange
strawberry
tomato
---
du -h를 통해 디스크 사용량을 출력하고, 해당 결과값을 sort로 출력한다.
여기서 'sort -h'를 통해 사람이 읽을 수 있는 숫자를 정렬하고 비교할 수 있다.
du -h | sort -h
0 ./ai
0 ./alphago
0 ./arduino
0 ./dir
0 ./dir3
0 ./.git/branches
0 ./.git/objects/info
0 ./.git/objects/pack
0 ./.git/refs/tags
0 ./images_mirror
0 ./IoT
0 ./mydir
0 ./mydir2
0 ./youtube
4.0K ./.git/info
4.0K ./.git/logs/refs/heads
4.0K ./.git/logs/refs/remotes
4.0K ./.git/logs/refs/remotes/origin
4.0K ./.git/objects/00
4.0K ./.git/objects/05
---
-r 옵션은 웬만하면 'reverse' 즉, 거꾸로 출력이라고 보면 된다.
sort -r fruits.txt
tomato
strawberry
orange
grapes
apple
---
sort의 옵션 'k'를 이용하면 sort 대상 필드를 선택할 수 있다.
sort -n -t$':' -k3 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
polkitd:x:999:998:User for polkitd:/:/sbin/nologin
docker:x:1000:1000:docker:/home/docker:/bin/bash
-n, --numeric-sort compare according to string numerical value # 숫자 순서대로
-t, --field-separator=SEP use SEP instead of non-blank to blank transition # 필드 구분자 지정
감사합니다.
'Cloud > Linux' 카테고리의 다른 글
shell-script로 계산기 만들기 (2) | 2022.02.11 |
---|---|
shell script master -9- (마지막) (0) | 2022.01.27 |
shell script master -7- (0) | 2022.01.27 |
shell script master -6- (0) | 2022.01.27 |
shell script master -5- (0) | 2022.01.21 |