Run The Bridge

shell script master -3- 본문

Cloud/Linux

shell script master -3-

anfrhrl5555 2022. 1. 5. 23:03
728x90
반응형

0. 쉘 스크립트란 무엇인가?

쉘(shell)은 명령 인터프리터로 사용자가 O/S에 대화식(interactively)으로 명령을 내리거나, 명령을 일괄(batch)적으로 실행할 수 있는 기능을 제공하는 응용 프로그램
  • Kernel
    • Core of the OS
    • Allocates time and memory to programs
  • Shell
    • Outer layer of OS
    • Interacts with user
    • Sends requests to kernel

쉘의 종류

  • sh(모든 O/S에서 지원한다)
  • csh
  • tcsh
  • ksh
  • bash(가장 유명하다)
  • zsh(인기)
  • dash

1. 스크립트 작성방법

#!/bin/bash  # 해당 코드를 입력한다. → 쉬뱅(해시뱅)
echo hello world

통상적으로 #!/bin/bash로 bash shell을 이용하여 실행시킨다.

---

root@kube-master ~/shell_script/shell_cmd # ./helloworld.sh
hello world

---

root@kube-master ~/shell_script/shell_cmd # ll /bin/bash
-rwxr-xr-x. 1 root root 964536 Nov 25 01:33 /bin/bash

---

#!/usr/bin/env bash  
echo hello world

bash의 경로가 현재 경로와 다른 경로에 위치할 경우, /usr/bin/env로 지정하고 bash를 입력해준다.

 

그러면 bash의 경로가 /bin/bash에 위치하지 않아도 동작한다.

---

root@kube-master ~/shell_script/shell_cmd # ps
   PID TTY          TIME CMD
 37113 pts/0    00:00:00 bash
 40931 pts/0    00:00:00 ps

우리는 ps명령을 통해 bash가 항상 bg상에서 동작하고 있는 것을 알 수 있다.


2. DOS 스타일의 줄끝

\n: 줄 바꿈 문자(Line Feed, 10, 0x0A)


다음 게시글을 참고하면 도움이 된다!

https://anfrhrl5555.tistory.com/113?category=999265 

 

CR/LF

코딩을 하다 보면 CR/LF라고 적혀있는 단어를 많이 보게 되는데 과연 무엇을 뜻하는 걸까? 밑의 사진은 notepad++의 하단 바에 위치한 내용이다. 역시 Windows(CR LF)라고 적혀있다. 오른쪽 버튼을 눌렀

anfrhrl5555.tistory.com


Linux의 hello.txt를 hexdump로 16진수 출력을 하면, '0a'를 통해 줄 바꿈을 실행하고 있다.

root@kube-master ~/shell_script/shell_cmd # hexdump -C hello.txt
00000000  68 65 6c 6c 6f 0a                                 |hello.|
00000006

---

마찬가지로 윈도우에서의 실행을 확인해보면 '0a 0d'로 CRLF를 통해 줄 바꿈을 실행하고 있다.

root@kube-master ~/shell_script/shell_cmd # hexdump -C hello_ms.txt
00000000  68 65 6c 6c 6f 0a 0d                              |hello..|
00000007

3. 스크립트의 실행방법 4가지

 0. 실행 권한 +x 부여 후./로 실행한다.

root@kube-master ~/shell_script/shell_cmd # chmod +x helloworld.sh
root@kube-master ~/shell_script/shell_cmd #
root@kube-master ~/shell_script/shell_cmd # ./helloworld.sh
hello world

 1. bash를 붙여서 실행한다.

root@kube-master ~/shell_script/shell_cmd # bash helloworld.sh

 2. source 명령어를 통해 실행한다.

root@kube-master ~/shell_script/shell_cmd # source helloworld.sh

 3. . 를 찍고 공백으로 실행한다.

root@kube-master ~/shell_script/shell_cmd # . helloworld.sh

 

※ 정리

0. chmod +x 후./ 로 실행

1. bash를 붙여서 실행

2. source를 붙여서 실행

3. . 공백으로 실행


4. 특수문자 종류 미리 보기

공백(white space)

  • 탭(Tab)
  • 줄 바꿈(newline)
  • 세로 탭
  • 양식 공급(form feed)
  • 캐리지 리턴(CR)
  • 공백(White Space)

Bash는 공백을 사용하여 단어의 시작과 끝을 결정한다.

 

사용자가 명령어를 입력할 시, 첫 번째 단어는 '명령 이름'이며, 추가 단어는 해당 명령에 대한 '인수'가 된다.

---

확장(EXPANSION)

  • parameter expansion(파라미터 확장)
    e.g. $var or ${var}
  • command substitution(명령 대체)
    e.g. $(command)
  • arithmetic expansion(산술 확장)
    e.g. $((expression))

---

큰 따옴표(Double Quotes) ""

  • \(백 슬래시)
  • $(달러)
  • `(백 쿼터)

위의 3가지로 특수문자를 제외한 특수문자는 일반 문자로 해석된다.

---

작은따옴표(Single Quote) ''

  • 모든 특수 문자의 해석이 방지된다.
    인용부호 안의 문자열 내용을 bash가 해석하지 않는다.
  • 특수 문자가 그대로 전달되며 여러 단어가 분할되지 않는다.
root@kube-master ~/shell_script/shell_cmd # echo "use: `basename $HOME` filename"
use: root filename

root@kube-master ~/shell_script/shell_cmd # echo 'use: `basename $HOME` filename'
use: `basename $HOME` filename

---

탈출(escape) '\'

  • 다음 문자가 특수 문자로 해석되는 것을 방지한다.
root@kube-master ~/shell_script/shell_cmd # echo "use: \`basename \$HOME\` filename"
use: `basename $HOME` filename

---

주석(comment) #

  • '#' 문자를 사용해 쉘에 의한 처리를 막는다.

---

테스트(Test) [[ ]]

  • 조건부 표현식이 "True" 인지 "False" 인지를 결정하기 위한 조건식의 평가

---

부정(negate) !

  • 테스트나 종료 상태를 무효화하거나 되돌리기 위해 사용한다.

---

방향 재지정(redirection)  >, <

  • 명령의 출력 또는 입력을 재 지정합니다.

0: stdin

1: stdout

2: stderr

---

파이프(PIPE) |

  • 초기 명령의 출력을 2차 명령의 입력으로 재 지정
root@kube-master ~/shell_script/shell_cmd # ls -al | wc -l
62

---

명령 분리자(command separator) ;

  • 같은 줄에 있는 여러 명령을 구분하는 데 사용한다.
root@kube-master ~/shell_script/shell_cmd # sum=0; while read num; do sum=$(($sum + $num)); done < numbers.txt; echo $num

---

인라인 그룹(inline group) {}

  • 중괄호 안의 명령은 마치 하나의 명령처럼 취급
  • bash 구문이 하나의 명령만을 필요로 하고, 함수의 사용은 피하고 싶을 때, 이것을 사용한다.

---

서브 셸 그룹(subshell group) ()

  • 위와 비슷하지만 내부 명령이 서브 쉘에서 실행되는 경우
  • 명령이 부작용을 일으키는 경우 샌드박스처럼 많이 사용된다.
  • 현재 쉘에는 영향을 주지 않음

---

산술 표현식(arithmetic expression)

  • +, -, *, / 같은 수학 연산자
  • (( a=1+4)), if (( a < b ))

---

산술 확장(arithmetic expansion) $(())

  • 위와 유사하지만 표현식은 산술 계산 결과로 대체된다.
root@kube-master ~/shell_script/shell_cmd # a=5 b=10

root@kube-master ~/shell_script/shell_cmd # echo "The average is $(( (a+b)/2 ))"
The average is 7

---

홈 디렉터리(home dir) ~


5. 쉘 변수

root@kube-master ~/shell_script/shell_cmd # animal=tiger

---

대입 연산자를 초기화할 때는, 좌 우측에 공백 문자가 존재해선 안된다.

root@kube-master ~/shell_script/shell_cmd # animal =tiger
-bash: animal: command not found

---

color=white라는 변수를 만든다.

root@kube-master ~/shell_script/shell_cmd # color=white

---

변수를 참조할 때는 반드시 좌측에 '$'이 있어야 한다.

root@kube-master ~/shell_script/shell_cmd # echo "tiger's color is $color"
tiger's color is white

6. 파라미터 대체와 인용부호

root@kube-master ~/shell_script/shell_cmd # book="The old man and the sea.mp3"

---

다음과 같이 rm $book를 하여도 삭제가 되지 않는다. 

root@kube-master ~/shell_script/shell_cmd # rm $book
rm: cannot remove ‘The’: No such file or directory
rm: cannot remove ‘old’: No such file or directory
rm: cannot remove ‘man’: No such file or directory
rm: cannot remove ‘and’: No such file or directory
rm: cannot remove ‘the’: No such file or directory

---

파일을 삭제할 때의 방법에 문제가 있다. ""로 묶어줘야 한다.

root@kube-master ~/shell_script/shell_cmd # rm "$book"

---

다음과 같이 두 개의 변수를 ';'를 이용해 선언한다.

root@kube-master ~/shell_script/shell_cmd # animal=Tiger; color=Red

---

아래와 같이 출력하면? 복수형으로 출력되지 않고, 그 자체를 단어로 본다.

root@kube-master ~/shell_script/shell_cmd # echo "$animals $colors"

---

'{}'를 이용하여 변수의 범위를 지정해 준다.

root@kube-master ~/shell_script/shell_cmd # echo ${animal}s vs. ${color}s
Tigers vs. Reds

---

인용부호("")를 써서 조금 더 확실하게 해 준다.

root@kube-master ~/shell_script/shell_cmd # echo "${animal}s vs. ${color}s"
Tigers vs. Reds

7. 특수 매개변수

다음과 같은 스크립트 파일을 작성한다.

# whereis.sh
#!/bin/bash
DIRECTORY=`dirname $0`  # $0 특수인용부호
echo $DIRECTORY

---

결과로 전체 경로를 출력하는 것을 알 수 있다.

root@kube-master ~/shell_script/shell_cmd # /root/shell_script/shell_cmd/whereis.sh
/root/shell_script/shell_cmd

---

whois.sh라는 쉘 스크립트를 작성한다.

# whois.sh
#!/bin/bash
name=$1  # 1번째 전달인자
email=$2  # 2번쨰 전달인자
all=$*  # 모든 전달인자

echo "your name is $name"
echo "your email is $email"
echo "* is $all"

---

전달 인자가 없어서 is 뒤에 값이 없다.

 

전달 인자를 준다.

root@kube-master ~/shell_script/shell_cmd # ./whois.sh
your name is
your email is
* is

---

                                                 $0      $1       $2
root@kube-master ~/shell_script/shell_cmd # ./whois.sh james james@gmail.com
your name is james
your email is james@gmail.com
* is james james@gmail.com

---

Name Usage Description
0 $0 스크립트의 이름 또는 경로를 포함
1 2 etc $1 etc 위치 매개 변수에는 현재 스크립트 또는 함수에 전달된 인수가 포함
* "$*" 모든 위치 매개 변수의 모든 단어로 확장된다. 큰 따옴표를 붙이면, IFS 변수의 첫 번째 문자로
분리된 모든 문자열을 포함하는 단일 문자열로 확장된다.
@ $@ 모든 위치 매개 변수의 모든 단어로 확장된다. 큰 따옴표로 묶어서 개별 단어로 모두 목록으로 확장
# $# 위치 매개변수의 갯수가 저장된다.
? $? 가장 최근에 완료한 foreground 명령의 종료 코드로 확장한다.
$ $$ 현재 쉘의 PID으로 확장한다.
! $! 백그라운드에서 가장 최근에 실행 된 명령의 PID로 확장한다.
_ $_ 실행된 마지막 명령의 마지막 인수로 확장한다.

---

인수가 잘 넘어가는지 확인하는 스크립트 코드를 작성한다.

#!/bin/bash
name=$1
email=$2
all=$*

if [ $# -eq 0 ]
then
 echo "No arguments supplied"
fi

echo "$#"  # $#의 값을 이해를 쉽게하기 위해 출력
echo "your name is $name"
echo "your email is $email"
echo "* is $all"

---

매개변수 값이 늘 때마다 1씩 증가하면서 카운팅 되고 있다.

root@kube-master ~/shell_script/shell_cmd # ./whois.sh one
1
your name is one
your email is
* is one
root@kube-master ~/shell_script/shell_cmd # ./whois.sh one two
2
your name is one
your email is two
* is one two
root@kube-master ~/shell_script/shell_cmd # ./whois.sh one two three
3
your name is one
your email is two
* is one two three
root@kube-master ~/shell_script/shell_cmd # ./whois.sh one two three four
4
your name is one
your email is two
* is one two three four
root@kube-master ~/shell_script/shell_cmd # ./whois.sh one two three four five
5
your name is one
your email is two
* is one two three four five

8. 환경 변수

미리 예약된 UID 같은 값을 환경변수라고 부른다.

root@kube-master ~/shell_script/shell_cmd # echo "USER ID: $UID"
USER ID: 0

---

# euid.sh
#!/bin/bash

if [ "$EUID" -ne 0 ]; then  # non equal
  echo "run as root"
  exit
fi
echo hello

---

oot@kube-master ~/shell_script/shell_cmd # ./euid.sh
run as root  # root, 즉 UID가 0인 값으로 실행해야 한다.

---

root@kube-master ~/shell_script/shell_cmd # sudo ./euid.sh
hello

---

root@kube-master ~/shell_script/shell_cmd # echo "$RANDOM"
6603
root@kube-master ~/shell_script/shell_cmd # echo "$RANDOM"
28720
root@kube-master ~/shell_script/shell_cmd # echo "$RANDOM"
28531
root@kube-master ~/shell_script/shell_cmd # echo "$RANDOM"
9785
root@kube-master ~/shell_script/shell_cmd # echo "$RANDOM"
29900

---

이러한 환경변수는 ENV라는 명령을 통해 볼 수 있다.

root@kube-master ~/shell_script/shell_cmd # env
XDG_SESSION_ID=13
HOSTNAME=kube-master
SELINUX_ROLE_REQUESTED=
TERM=xterm
SHELL=/bin/bash
HISTSIZE=1000
.
.
.LESSOPEN=||/usr/bin/lesspipe.sh %s
XDG_RUNTIME_DIR=/run/user/0
_=/usr/bin/env

9. declare

-a 옵션을 통해 배열을 사용할 수 있다.

root@kube-master ~/shell_script/shell_cmd # declare -a alnum=(al b1 c1 d1 e1 f1)

---

Array의 시작은 항상 0번!

root@kube-master ~/shell_script/shell_cmd # echo ${alnum[0]}
a1
root@kube-master ~/shell_script/shell_cmd # echo ${alnum[1]}
b1
root@kube-master ~/shell_script/shell_cmd # echo ${alnum[2]}
c1
root@kube-master ~/shell_script/shell_cmd # echo ${alnum[3]}
d1

---

-i 옵션을 줘서 78이라는 정수형 변수를 사용할 수 있다.

root@kube-master ~/shell_script/shell_cmd # declare -i inum=78

root@kube-master ~/shell_script/shell_cmd # inum=inum+1

root@kube-master ~/shell_script/shell_cmd # echo $inum
79

---

그러면 -i 옵션을 안 쓰고 그냥 변수에 할당해줘도 되는 거 아니야?라고 생각할 수 있지만 \

 

Shell에서는 78이라는 값을 숫자로 보지 않고 string으로 보기 때문에 값이 더해지지 않는다.

root@kube-master ~/shell_script/shell_cmd # num=78

root@kube-master ~/shell_script/shell_cmd # num=num+1

root@kube-master ~/shell_script/shell_cmd # echo $num
num+1

---

-r 옵션을 줘서 ReadOnly로 설정할 수 있다.

root@kube-master ~/shell_script/shell_cmd # declare -r rPi=3.14

root@kube-master ~/shell_script/shell_cmd # rPi=999
-bash: rPi: readonly variable

---

-x 옵션을 줘서 변수를 export 할 수 있다.

root@kube-master ~/shell_script/shell_cmd # declare -x xpath="${HOME}/Desktop/mydir"

root@kube-master ~/shell_script/shell_cmd # echo $xpath
/root/Desktop/mydir

다음과 같다

export XPATH="${HOME}/Desktop/mydir"

※ 정리
-a : arryay, 배열 생성
-i : integer, 정수형 변수 생성
-r: ReadOnly, 읽기 전용
-x : Export, PATH설정


10. 매개변수 확장(PE)

다음과 같은 문자열을 만든다.

root@kube-master ~/shell_script/shell_cmd # testString="That that is is that that is not is not"

---

변수에 할당된 문자의 개수를 Count 할 수 있다.

root@kube-master ~/shell_script/shell_cmd # echo ${#testString}
39

---

아래와 같이 시작 index를 설정하여 그 index부터 출력할 수 있다.

root@kube-master ~/shell_script/shell_cmd # echo ${testString:0}
That that is is that that is not is no

---

인덱스 값을 1로 조절하면 'hat'부터 시작된다.

 

(파이썬의 Array 하고 비슷하면서 다르네 ㅡㅡ..;)

root@kube-master ~/shell_script/shell_cmd # echo ${testString:1}
hat that is is that that is not is no

---

문자열의 시작과 끝을 지정해줄 수 있다.

root@kube-master ~/shell_script/shell_cmd # echo ${testString:3:3}
t t
-----
아래의 값이 t that is ~~ 이다.
root@kube-master ~/shell_script/shell_cmd # echo ${testString:3}
t that is is that that is not is no

That that is ~~~

T = 0
h = 1
a = 2
t = 3 하고 t부터 공백문자 포함 3개의 글자 t까지 출력되는 것을 알 수 있다.

인덱스처럼 0으로 시작한는 것이 아니라 1부터 글자 수를 카운팅한다고 보면 된다.

---

대문자 T로 시작하는 문자열을 잘라내기 할 수 있다.

testString=That that is is that that is not is not

root@kube-master ~/shell_script/shell_cmd # echo ${testString#T*is}
is that that is not is not

'That that is'까지 잘라내기 한 것을 확인할 수 있다.

---

'##'를 두 개 써주면 더 이상 is가 나오지 않을 때까지 잘라내기를 한다.(정규표현식이랑 비슷)

root@kube-master ~/shell_script/shell_cmd # echo ${testString##T*is}
no

---

앞에서부터 지웠다면, '%' 기호를 사용하여서 뒤에서부터 제거할 수 있다.

root@kube-master ~/shell_script/shell_cmd # echo ${testString%is*not}
That that is is that that is not

---

마찬가지로 '%%'를 사용해서 더 이상 값(is)이 나오지 않을 때까지 삭제할 수 있다.

root@kube-master ~/shell_script/shell_cmd # echo ${testString%%is*not}
That that

---

'//' 뒤에 있는 단어와 매칭 되는 모든 단어들이 제거된다.

root@kube-master ~/shell_script/shell_cmd # echo ${testString//that}
That is is is not is not

---

's//g'와 비슷한데, 'that'이라는 단어를 'this'라는 단어로 치환한다. but, 매칭이 일어난 한 개의 단어만 바뀌었다.

root@kube-master ~/shell_script/shell_cmd # echo ${testString/that/this}
That this is is that that is not is not

---

대, 소문자 상관없이 'this'로 치환하지만 한 개의 단어만 치환한다.

root@kube-master ~/shell_script/shell_cmd # echo ${testString/[tT]hat/this}
this that is is that that is not is not

---

'//' 두 개를 써서 대, 소문자 상관없이 'this'로 치환한다.

root@kube-master ~/shell_script/shell_cmd # echo ${testString//[tT]hat/this}
this this is is this this is not is not

---

'#'를 사용하여 앞부분부터 바꿔줄 수도 있다.

root@kube-master ~/shell_script/shell_cmd # echo ${testString/#That/this}
this that is is that that is not is not

---

'%'를 사용하면 마지막에서부터 바꿀 수 있다.

root@kube-master ~/shell_script/shell_cmd # echo ${testString/%not/NO}
That that is is that that is not is NO

 

※ 정리

testString="That that is is that that is not is not"

echo ${#testString}  # 문자의 개수를 Count 할 수 있다.

echo ${testString:0}  # 0번째 인덱스부터 출력한다.

echo ${testString3:3}  # 3번째 인덱스부터 공백포함 3글자 출력한다

echo ${testString#T*is}  # 대문자 T로 시작하는 문자열이과 첫번째 is까지 있는 모든 문자를 삭제한다.

echo ${testString##T*is}  # is가 더이상 나오지 않을 때 까지 삭제한다.

echo ${testString%is*not}  # '%'를 사용해서 뒤에서 부터 삭제할 수 있다.

echo ${testString%%is*not}  # '%%'를 사용해서 해당 문자열이 더 이상 나오지 않을 때 까지 삭제한다.

echo ${testString//that}  # '//'뒤에있는 문자와 매칭되는 모든 단어를 삭제한다. 

echo ${testString/that/this}  # that를 this로 치환한다. ※ 한 개의 단어만 매칭되며 치환된다.

echo ${testString/[tT]hat/this}  # 대, 소문자 상관없이 this로 치환한다. ※ 한 개의 단어만 매칭되며 치환된다.

echo ${testString//[tT]hat/this}  # '//' 두 개를 사용해 대, 소문자 상관없이 모든 단어를 'this'로 치환한다.

echo ${testString/#[tT]hat/this}  # '#'를 사용하여 앞부분에서 부터 바꿔줄 수 있다.

echo ${testString/%not/NO}  # '%'를 사용하여 끝에서 부터 바꿀 수 있다.

11. globe 패턴

echo ???  # 3글자인 이름을 출력한다.
bin dev etc lib mnt opt run srv sys tmp usr var

echo ????  # 4글자인 이름을 출력한다.
boot home proc root sbin

echo b??  # b로 시작하는 3글자 이름을 출력한다.
bin

echo b*  # b로 시작하는 모든 이름을 출력한다.
bin boot

echo [abcd]*  # a, b, c, d 모두 매칭되는 이름을 출력한다.
bin boot dev

echo [a-d]*  # 범위를 지정해 줄 수 있다.
bin boot dev

12. 명령어(tr)

root@kube-master /etc/kubernetes # echo "Hello world"
Hello world

---

'tr'를 사용하면 단어를 스페이스바를 기준으로 치환할 수 있다. '<<<'는 히어스트링이라고 부른다.

root@kube-master /etc/kubernetes # tr abcdefgijklmnopqrstuvwxyz ZABCDEFGHIJKLMNOPQRSTUVWXYZ <<< "Hello World"
HDJJM WMPJC

---

※ Camel Case: 단어의 첫 글자를 대문자로 표현하는 경우, 낙타의 등처럼 보인다고 해서 붙어진 용어

root@kube-master /etc/kubernetes # tr [:lower:] [:upper:] <<< "Hello World"
HELLO WORLD

소문자를 대문자로 바꿔주는 스크립트

---

공백 문자를 Tab문자로 치환한다.(4칸 띄어쓰기된다)

root@kube-master /etc/kubernetes # tr [:space:] '\t' <<< "Hello Wolrd"
Hello   Wolrd

---

-s(Squeeze): 반복되는 글자를 1글자로 축약

root@kube-master /etc/kubernetes # tr -s [:space:] <<< "Hello                World"
Hello World

---

-d(delete): 공백문자 제거

root@kube-master /etc/kubernetes # tr -d [:space:] <<< "Hello             World"
HelloWorld

---

-cd(Complement): 지정한 글자를 제외한 다른 글자를 뜻한다.

root@kube-master /etc/kubernetes # tr -cd [:space:] <<< "Hello              World"

---

다음과 같이 사용하면, 알파벳은 남고 공백이 사라진다.

root@kube-master /etc/kubernetes # tr -cd [:alpha:] <<< "Hello              World"
HelloWorld

---

root@kube-master /etc/kubernetes # tr --help
Usage: tr [OPTION]... SET1 [SET2]
Translate, squeeze, and/or delete characters from standard input,
writing to standard output.

  -c, -C, --complement    use the complement of SET1
  -d, --delete            delete characters in SET1, do not translate
  -s, --squeeze-repeats   replace each input sequence of a repeated character
                            that is listed in SET1 with a single occurrence
                            of that character
  -t, --truncate-set1     first truncate SET1 to length of SET2
      --help     display this help and exit
      --version  output version information and exit

SETs are specified as strings of characters.  Most represent themselves.
Interpreted sequences are:

  \NNN            character with octal value NNN (1 to 3 octal digits)
  \\              backslash
  \a              audible BEL
  \b              backspace
  \f              form feed
  \n              new line
  \r              return
  \t              horizontal tab
  \v              vertical tab
  CHAR1-CHAR2     all characters from CHAR1 to CHAR2 in ascending order
  [CHAR*]         in SET2, copies of CHAR until length of SET1
  [CHAR*REPEAT]   REPEAT copies of CHAR, REPEAT octal if starting with 0
  [:alnum:]       all letters and digits
  [:alpha:]       all letters
  [:blank:]       all horizontal whitespace
  [:cntrl:]       all control characters
  [:digit:]       all digits
  [:graph:]       all printable characters, not including space
  [:lower:]       all lower case letters
  [:print:]       all printable characters, including space
  [:punct:]       all punctuation characters
  [:space:]       all horizontal or vertical whitespace
  [:upper:]       all upper case letters
  [:xdigit:]      all hexadecimal digits
  [=CHAR=]        all characters which are equivalent to CHAR

Translation occurs if -d is not given and both SET1 and SET2 appear.
-t may be used only when translating.  SET2 is extended to length of
SET1 by repeating its last character as necessary.  Excess characters
of SET2 are ignored.  Only [:lower:] and [:upper:] are guaranteed to
expand in ascending order; used in SET2 while translating, they may
only be used in pairs to specify case conversion.  -s uses SET1 if not
translating nor deleting; else squeezing uses SET2 and occurs after
translation or deletion.

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
For complete documentation, run: info coreutils 'tr invocation'

13. 명령어(cut) ★

root@kube-master ~/shell_script/shell_cmd # cat fruits.txt
grapes
orange
tomato
strawberry
apple

---

2번째 char만 뽑아내서 출력한다.

root@kube-master ~/shell_script/shell_cmd # cut -c2 fruits.txt
r
r
o
t
p
roo

---

마찬가지로 범위 지정 가능

root@kube-master ~/shell_script/shell_cmd # cut -c1-3 fruits.txt
gra
ora
tom
str
app

---

passwd 파일에 첫 번째(사용자 이름) 필드를 가져오는 스크립트

 

-d(delimiter)는 콜론(:)으로 설정한다.

 

-f(field)1 → 첫 번째 필드만 가져온다.

root@kube-master ~/shell_script/shell_cmd # cut -d':' -f1 /etc/passwd
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
games
ftp
nobody
systemd-network
dbus
polkitd
tss
abrt
sshd
postfix
docker

---

아래의 ens32에서 IP 부분만 cut으로 잘라봤다.

root@kube-master ~/shell_script/shell_cmd # /sbin/ifconfig ens32
ens32: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.200.171  netmask 255.255.255.0  broadcast 192.168.200.255
        inet6 fe80::20c:29ff:feee:cc1e  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:ee:cc:1e  txqueuelen 1000  (Ethernet)
        RX packets 405284  bytes 527822549 (503.3 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 207593  bytes 45406162 (43.3 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

 

교육영상이랑 조금 달라서 약간의 수정을 했다.

/sbin/ifconfig ens32 | grep -ie 'inet* [1-9]' | awk '{print $2}'
192.168.200.171

14. 확장 glob

디렉토리에 파일들이 아래와 같이 존재한다.

root@kube-master ~/shell_script/shell_cmd/images # ls -al
total 4
drwxr-xr-x.  2 root root  151 Jan  6 22:16 .
drwxr-xr-x. 12 root root 4096 Jan 13 21:09 ..
-rw-r--r--.  1 root root    0 Jan  6 22:16 Balloon.jpg
-rw-r--r--.  1 root root    0 Jan  6 22:16 Candy.jpg
-rw-r--r--.  1 root root    0 Jan  6 22:16 glob.gif
-rw-r--r--.  1 root root    0 Jan  6 22:16 settings_down.png
-rw-r--r--.  1 root root    0 Jan  6 22:16 settings_up.png
-rw-r--r--.  1 root root    0 Jan  6 22:16 shadingimage.tiff
-rw-r--r--.  1 root root    0 Jan  6 22:16 smaller.tiff

---

jpg, bmp만 보고 싶을 때

root@kube-master ~/shell_script/shell_cmd/images # echo *jpg *bmp
Balloon.jpg Candy.jpg *bmp

---

확장글로브는 기본값이 disable이므로 아래의 명령으로 enable 할 수 있다.

shopt -s extglob

---

부정문 '!'를 사용해서 이외의 것을 출력할 수 있다.

root@kube-master ~/shell_script/shell_cmd/images # echo !(*jpg|*bmp)
glob.gif settings_down.png settings_up.png shadingimage.tiff smaller.tiff

---

'@'를 사용할 수도 있는데 'or'의 뜻을 갖는다.

root@kube-master ~/shell_script/shell_cmd/images # echo @(*jpg|*bmp)
Balloon.jpg Candy.jpg

---

globs에서 사용할 수 있는 메타 문자들

Name Description
?( list ) 주어진 패턴의 0번 또는 1번 일치
*( list ) 주어진 패턴의 0회 이상 일치
+( list ) 주어진 패턴의 하나 이상의 일치(AND)
@( list ) 주어진 패턴 중 하나와 일치(OR)
! ( list ) 주어진 패턴을 제외한 모든 것(NOT)

15. 쉘 스크립트 문법 검사 도구

쉘 스크립트 정적 분석 도구로 유용한 웹사이트

https://www.shellcheck.net/

 

ShellCheck – shell script analysis tool

ShellCheck finds bugs in your shell scripts

www.shellcheck.net


16. 컬러(color) 테스트

PASS


17. 실습(DRILL)

터미널 Prompt를 Color로 바꿔보세요!


감사합니다.

728x90
반응형

'Cloud > Linux' 카테고리의 다른 글

shell script master -5-  (0) 2022.01.21
shell script master -4-  (0) 2022.01.13
i-node 실습  (0) 2022.01.12
shell script master -2-  (0) 2022.01.03
shell script master -1-  (2) 2022.01.03
Comments