본문 바로가기
Programming Skills/Shell

[Shell] 리다이렉션(Redirection)

by jungcow 2021. 5. 29.
  • 리다이렉션을 구현하기에 앞서 어떤 것인지 여기 에서 알아보자

리다이렉션 구현하기

1. input redirect

< file1 cat
  • 위처럼 < 가 왼쪽을 향하고 있으면 input으로 명령어에 들어간다는 뜻이다.
  • 0< file1 cat
    • 위 명령 식과 동일하다.
    • 즉, < 앞에 0이 생략 되어있다.
  • 이를 구현하기 위한 예제 코드를 작성해보자.
    • 첫번 째 방법
      • #include <fcntl.h>
        #include <unistd.h>
        
        int        input_redirection()
        {
            close(STDIN_FILENO);
            input_fd = open(file1, O_RDONLY);
            if (input_fd < 0)
              return (ft_error_str(PERMISSION_ERR, file1));
            return (1);
        }
    • 두번째 방법
      • #include <fcntl.h>
        #include <unistd.h>
        
        int        input_redirection()
        {
            input_fd = open(file1, O_RDONLY);
            if (input_fd < 0)
              return (ft_error_str(PERMISSION_ERR, file1));
              dup2(input_fd, STDIN_FILENO);
              close(input_fd);
            return (1);
        }

2. output redirection

echo "hello" > file2
  • 위처럼 오른쪽으로 향하고 있으면 output을 file2로 한다는 뜻이다.
  • echo "hello" 1> file2
    • 위 명령 식과 동일하다.
    • 오른쪽 꺽쇠같은 경우엔 왼쪽에 1이 생략되어져 있다.
  • 예제
    • 첫번째 방법
      • #include <fcntl.h>
        #include <unistd.h>
        
        int        output_redirection()
        {
            close(STDOUT_FILENO);
            output_fd = open(file2, O_CREAT | O_WRONLY | O_TRUNC, 0644);
            if (output_fd < 0)
                return (ft_error_str(PERMISSION_ERR, file2));
            return (1);
        }
    • 두번째 방법
      • #include <fcntl.h>
        #include <unistd.h>
        
        int        output_redirection()
        {
            output_fd = open(file2, O_CREAT | O_WRONLY | O_TRUNC, 0644);
            if (output_fd < 0)
                return (ft_error_str(PERMISSION_ERR, file2));
          dup2(output_fd, STDOUT_FILENO);
          close(output_fd);
            return (1);
        }

3. Append redirection

echo "world" >> file2
  • 2개의 꺽쇠가 오른쪽으로 향하고 있으면 이는 file2의 내용 맨 아래에 world라는 글자를 덧붙힌다는 뜻이다.
  • echo "world" 1>> file2
    • 위 명령식과 동일하다.
  • 구현 코드
    • #include <fcntl.h>
      #include <unistd.h>
      
      int        output_redirection()
      {
          output_fd = open(file2, O_CREAT | O_WRONLY | O_APPEND, 0644);
          if (output_fd < 0)
              return (ft_error_str(PERMISSION_ERR, file2));
        dup2(output_fd, STDOUT_FILENO);
        close(output_fd);
          return (1);
      }
    • 위의 O_TRUNC 플래그를 O_APPEND 플래그로 수정해주기만 하면 된다.

4. Here Document

cat << HIHI
heredoc> hello
heredoc> world
heredoc> HIHI
hello
world
  • <<는 뒤의 HIHI를 read instruction으로 인식하고 HIHI를 다시 읽을 때까지 STDIN으로 input을 받아들인다.
  • 즉, 실행중에 임시파일을 만들어서 stdin에 연결되는 것이다.
  • 이는 script를 작성할 때 multi line으로 작성할 수 있게 해준다.
    • #!/bin/sh
      
      cat << EOF
      This is a simple lookup program 
      for good (and bad) restaurants
      in Cape Town.
      EOF
    • 결과:
      • This is a simple lookup program
        for good (and bad) restaurants
        in Cape Town.
  • 구현은 다음 기회에 해보자.

redirection 종류

No. Command & Description
1 program > file
프로그램의 출력을 file로 redirect 시킨다.
2 program < file
프로그램은 실행할 때 STDIN이 아닌 file에서 읽어온다.
3 program >> file
프로그램의 출력을 file에 덧붙힌다.
4 stream(fd)> file
특정 fd의 출력을 file로 redirect 시킨다.
5 stream(fd)>> file
특정 fd의 출력을 file에 덧붙힌다.
6 fd1>&fd2
fd1의 출력을 fd2로 병합 시킨다.
ex) asdf 2>&1 | grep command -> command를 grep으로 잡을 수 있게 된다.
7 fd1<&fd2
fd1의 입력을 fd2의 입력으로 병합시켜 읽어오게 된다.
8 << tag
tag를 다시 한번 읽어 올 때까지 들어가는 input은 모두 STDIN으로 redirect 된다.