Shell - 파이프 & 쉘 스크립트

dragonappear·2022년 1월 8일
0

Shell

목록 보기
4/7

Pipe and Filter

Pipe

  • 왼쪽 커맨드의 standard ouput과 오른족 커맨드의 standard inputd을 연결한다.
  • Individual program/commands know nothing about redirection and pipe
$ ls- -l | wc -l
5
$ who | wc -l
1

Filter

  • Filter
    • standard input으로 부터 데이터도 입력받고, standard output로 내보내는 명령어
    • standard input와 standard output 두 개 다 사용
    • cat,cut,awk,grep,wc,sort,bc,head, ...
  • 나머지
    • standard output만 사용하는 명령어
      • date,du,df,ls,pwd,who
    • 아무것도 사용하지 않는 명령어
      • mkdir,rmdir,cd
      • cp,mv,rm


Cut and Awk

cut

cut: 파일 혹은 standard input으로부터 문자 혹은 필드를 뽑아내는 명령어

-c : 문자단위로
-d : 구분자 사용
-f : 필드 번호
-f n1-n2 : 필드 범위

tr

tr: 문자를 변환하거나 삭제할때 사용하는 명령어

$ echo "abcde 12345" | tr 'bd' '*'
a*c*e 12345
$ echo "abcde 12345" | tr -d 'bd'
ace 12345
$ echo "abcde 12345" | tr -d ' '
abcde12345
$ echo "abcde 12345" | tr -d [:blank:] # 공백 뿐만 아니라 \t 등등도 포함
abcde12345
$ echo $PATH | tr ':' '\n' | wc -l
11

Awk

  • 특정 조건으로 데이터를 뽑아서 출력하는 명령어

  • cat sample | awk '{print $1}' : only action(no pattern)
  • cat sample | awk '$3==0 {print $1}'
  • cat sample | awk '$3>0 {print $1,$2*$3}'

  • 변수
    • 빌트인: NF(필드 넘버), NR(레코드 순서번호)
    • 필드: $0 $1 $2 ...
  • printf format conversion
    • %c: 아스키 char, %d: decimal number, %o: unsigned octal, ...
cat sample | awk 'NR!=2 {print $1,$2*$3,NF}'
cat sample | awk '$3>0 {printf("pay for %s is %.3f\n",$1,$3*$2)}'

Selection

  • Computation

    • cat sample | awk '$2$3>=100 {print $2$3,$1}'
    • 100 kim
    • 121 Song
  • Text content

    • cat sample | awk '$1~"Son" {print $2*$3,$1}'
    • 121 Song
    • cat sample | awk 's1=="Song" {print $2*$3,$1}'
    • 121 Song
  • Combinations (&& || !)

    • cat sample | awk '$2$3>=100&&$1~"Son" {print $2$3,$1}'
    • 121 Song

Example


Alias

  • 커맨드에 별칭을 달수있다.
  • current aliases 확인 : $ alias
  • to set alias: $ alias ll='ls -al'
  • remove alias: $ unalias ll


Shell Script

  • 쉘 스크립트는 subshell에서 실행된다.
  • Shabang: 쉘 스크립트를 실행할때 subshell을 생성한다.


Position Parameter

  • 쉘 스크립트에 인자를 전달하는 방법

  • 특정 쉘 파라미터

Example


User Input

  • 프로그램 수행 중에 동적으로 사용자로부터 입력을 받는 방법

0개의 댓글