리눅스 쉘
- 쉘은 사용자가 운영체제와 상호작용할 수 있도록 명령어를 입력받아 실행해주는 프로그램입니다.
- 모든 것은 파일이라는 철학 아래에서 인터렉션이 파일을 읽고 쓰는 것처럼 이루어져있음 (마우스, 키보드 디바이스 관련 기술도 포함)리눅스의 철학은 여러 기본단위의 프로그램들이 유기적으로 각자의 역할을 하면서, 이를 조합하여 전체 시스템이 동작하도록함.
- (ls | grep의 경우에도, lsgrep이란 명령어가 아닌 ls와 grep을 유기적으로 조합하여 사용함)
- 리눅스에는 여러가지 shell이 있지만 ubuntu에서도 그렇고 bash shell이 범용으로 쓰이기에 bash 명령어 위주로 학습할것.
- Bash: 기본적인 쉘로, 많은 시스템에서 기본으로 제공됩니다. 간단하고 강력하지만, Zsh에 비해 기능이 제한적입니다.
- Zsh는 Bash(Bourne Again Shell)처럼 널리 사용되는 쉘 중 하나로, Bash와 유사하지만 더 많은 기능과 사용자 친화적인 확장성을 제공합니다.
- 리눅스는 다중사용자를 전제로하며 사용자를 개인 그리고 그룹으로 구분하여 권한을 관리한다. root는 수퍼관리자이다.
- 리눅스는 커널동작과의 복잡하고 다양한 내용이 있어 필요에 따른 선별적으로 공부가 필요하다.
What is a Shell Script?
A shell script is a text file containing a sequence of commands for a Unix-based operating system's shell to execute.
#!/bin/bash
echo "Hello, world!"
mkdir my_folder
cd my_folder
touch file.txt
Why is it called a "Shell Script"?
- Shell: Refers to the command-line interface (like bash, sh, zsh) that acts as a "shell" — a layer between the user and the operating system.
- The term "shell" was used because it's the outer layer that wraps around the kernel (the core of the OS), allowing users to interact with the system.
- Script: Because it's a file containing a series of commands, just like a script in a play or a program.
What is a Shell?
A shell (like /bin/sh, bash, or zsh) is:
A scripting language and interpreter that lets users type commands and write scripts to control and combine programs.
Key Roles:
- Parses user input (e.g., ls -al | grep foo)
- Understands and interprets:
- Pipes (|), redirection (>, <)
- Control structures (if, for, while)
- Variables ($HOME, $1)
- Launches programs by calling system-level functions
What is ls?
ls is an independent compiled program (usually at /bin/ls) that lists files in a directory.
Key Points:
- Not part of the shell
- The shell just calls it
- Works on its own even outside the shell (e.g., in Java, C, etc.)
The Relationship:
The shell is the “glue” that connects and coordinates small programs like ls, grep, awk, ffmpeg, etc., using its own scripting logic.
리눅스 쉘 사용법 정리
유용한 보조기능
- Tab 키
- 명령어 자동 완성: 터미널에서 명령어 입력 중 Tab 키를 누르면 자동 완성됩니다.
- 명령어 제안: 명령어나 파일명의 일부를 입력하고 Tab 키를 두 번 누르면 가능한 명령어 목록을 표시합니다.
- 위쪽 화살표: 이전에 입력했던 명령어들을 순환하며 다시 사용할 수 있습니다.
리눅스 기본명령어
- VARIABLE_NAME (변수정의) ="value"(값정의)
- Quotes are optional only when the value is plain and safe, like a single word or filename with no spaces.
Quote Types | Behavior |
"double" | Allows variable substitution ($VAR) and command substitution (`pwd`) |
'single' | Takes everything literally — no $VAR, no command substitution |
(none) | Risky if value contains spaces or special characters |
- $VARIABLE(변수호출) : Use $ to refer to the variable:
- $(명령어) : 명령어치환기능으로 어떤 명령어의 실행 결과를 다른 명령어의 인자로 사용하는 기능
- docker stop $(docker ps -q) : 현재 실행중인 모든 컨테이너 종료
- export $ (변수전달) : makes a environment variable available to child processes
- It creates an environment variable for the current terminal session only. Used You want to configure the OS or shell-level settings,
- echo "String/Variable" (값 터미널 출력) : Prints the value
- man '명령어': 명령어의 메뉴얼 페이지로 이동해 모든 옵션을 조회합니다. ''로 메뉴얼 페이지에서 나올 수 있습니다.
- clear: 이전에 입력한 명령어 기록을 삭제합니다.
- exit: 시스템을 종료합니다.
- sleep: 지정된 시간 동안 아무 작업도 하지 않는 프로세스를 실행합니다.
- *: 모든 파일이나 디렉토리와 일치합니다.
- '테이블/컬럼명 as 별칭': 테이블이나 컬럼명을 지정한 별칭으로 표시합니다.
- desc '테이블명': 테이블의 모든 컬럼 정보를 표시합니다.
스크립트 해석
- 스크립트 해석순서
- Basically Shell parses from left to right
- Variable assignments are evaluated before the command runs
- Pipes (|), redirects (>, <), logical operators (&&, ||) are parsed based on shell grammar and grouping
- 리다이렉션과 파이프
- 하나의 프로세스는 반드시 stdin stdout stderr 3가지 스트림(경로)를 갖고 있음. 이는 프로그램으로의 input과 output, error 메세지의 이동경로를 말하며 stdout과 stderr은 기본적으로 콘솔출력창으로 향함
- >,< : 명령어 표준 출력을 콘솔창이 아닌 파일에 작성할때 사용함(>), 반대로 파일의 내용물을 프로그램의 입력으로 사용(<). 파일에 작성시 파일이 존재하지않으면 파일을 생성함
- head < file : 파일의 최초 10줄만 출력함 (파일 읽기 명령어는 file 에서 명령어 변수로 stream이 이동되나 일반적으로 생략됨)
- >>,<< : 기존 입력내용에 내용을 추가하고싶으면 본 기호를 사용함.
- 파이프(|) : 파이프 앞의 프로세스의 출력이 그 다음 프로세스의 입력으로 사용. (ls | grep ab ; ab를 포함한 스트림만 출력, 폴더 내의 파일을 찾을 때 유용함 )
프로세스 실행관련
- #!/bin/sh(스크립트시작) : execute this script using /bin/sh (a shell interpreter).”
- #! : special character sequence that tells the system this is a script.
- /bin/sh → the interpreter to use (in this case, the sh shell).
- nohup(지속프로세스실행) : Stands for “no hang up”, Allows the process to keep running even after you log out of the terminal.
- & : This runs the entire command in the background. So the shell doesn't wait — you get your prompt back immediately.
- 'process start cmd' > /dev/null 2>&1 (출력결과 무시)
- > /dev/null : redirect standard output (stdout, file descriptor 1) to /dev/null.
- /dev/null is a special file that discards everything — a "black hole."
- redirect standard error (stderr, file descriptor 2) to wherever 1 (stdout) is currently going.
- At this point, stdout is already redirected to /dev/null, so stderr goes there too.
- > /dev/null : redirect standard output (stdout, file descriptor 1) to /dev/null.
권한관리
- chmod [숫자] [파일명] : 파일이나 디렉토리의 권한을 변경합니다. 예: chmod 755 파일명
- 숫자규칙 : 소유자+그룹+기타 순으로 자릿수가 매겨짐
- r은 4, w는 2. x는 1이며 이것의 합이 각 주체의 자릿수에 간다
- chmod -R [숫자] [파일명] : -R옵션은 directory의 모든 파일의 권한을 일괄적으로 바꾼다
- 숫자규칙 : 소유자+그룹+기타 순으로 자릿수가 매겨짐
- whoami: 현재 로그인한 사용자 ID를 표시합니다.
- root는 슈퍼관리자ID이고 모든 권한이 부여되기때문에 파일을 삭제시 복구가 어려우므로 root라는 사용자는 잘사용하지 않는다. 대신, 슈퍼관리자권한이 필요할때 sudo 명령어를 사용한다.
- sudo: 관리자 권한으로 명령을 실행합니다. 예: sudo apt-get update
- 일부 애플리케이션은 Unix Socket 인증인 sudo를 통해 자동 인증하여 root 계정을 사용하도록 설정됨. Unix 소켓(Unix Domain Socket, UDS)을 사용하여 운영체제의 사용자 계정과 애플리케이션 계정을 연결하는 인증 방식.
- unix 소켓이란 : 운영체제(로컬) 내에서 파일시스템을 통해서 송수신이 실행되는 프로세스 간 통신(IPC, Inter-Process Communication)을 위한 소켓
- 즉,운영체제의 사용자 계정을 확인하여 로그인 권한을 부여하는 방식. 현재 리눅스 사용자가 root라면, MariaDB에서도 root로 로그인할 수 있도록 자동 인증해주는 거야.
- 따라서, sudo mysql -u root 또는 mysql -u root만 입력하면 자동으로 로그인됨.
- apt-get update는 시스템업데이트로 관리자권한이 필요한데 sudo로 실행시켜야만 실행가능
- 일부 애플리케이션은 Unix Socket 인증인 sudo를 통해 자동 인증하여 root 계정을 사용하도록 설정됨. Unix 소켓(Unix Domain Socket, UDS)을 사용하여 운영체제의 사용자 계정과 애플리케이션 계정을 연결하는 인증 방식.
네트워크 관리
- ssh -i [filepath]: Secure Shell, 보안 네트워크를 통해 다른 컴퓨터에 안전하게 원격 접속합니다.
- -i [filepath] : The -i option specifies the path to the file that contains the private key used for authentication.
- ifconfig: 네트워크 인터페이스와 IP 정보를 확인합니다.
파일시스템 관리
- mkdir 'name': 새 디렉토리를 생성합니다.
- rm [options] [filepath] : remove, 파일이나 디렉토리를 삭제합니다. 리눅스는 휴지통이란 기능이 없기때문에 매우 조심스럽게 사용해야하며, 그러므로 root와 같은 슈퍼관리자로는 작업을 안함.
- -r옵션 : recursive, 하위디렉토리를 포함한 모든 파일 삭제
- -f옵션 : force, 강제로 파일이나 디렉토리 삭제
- 예: rm -rf 디렉토리명: 현재 directory 내의 directory1 하위의 모든 것 삭
- cd: change directory, 다른 디렉토리로 이동합니다.
- 키워드 : '/' : root, '..' 상위디렉토리, '.' 현재디렉토리 '~' 사용자의 홈폴더, '-' : 이전에 있었던 폴더
- 참조방식 : 절대참조 /home/ubuntu/temp.txt, 상대참조 ./temp.txt
- cat '파일명': concatenation, 파일의 내용을 출력합니다.
- pwd: print working directory, 현재 디렉토리의 경로를 표시합니다.
- ls: list, 디렉토리 내용을 나열합니다
- -a : 숨김파일까지 조회, '.'으로 시작하는 파일은 주로 숨김파일 및 폴더임
- -l :파일의 정보를 상세하게 확인함
- ls의 조회결과
- 파일 타입: 각 항목의 첫 글자는 파일의 타입을 나타냅니다.
- d: 디렉토리
- -: 일반 파일
- l: 링크 파일(바로가기)
- 권한: 각 파일의 접근 권한을 나타내며, 세 부분으로 나뉩니다.
- 생성자 권한 (rwx): 읽기(r), 쓰기(w), 실행(x), r: read, w:write, x:execute
- 그룹 권한 (rwx): 그룹 사용자의 읽기, 쓰기, 실행 권한
- 기타 사용자 권한 (rwx): 그룹이나 소유자에 속하지 않는 사용자의 권한
- 링크 개수: 해당 파일이나 디렉토리가 몇 개의 링크를 가지고 있는지 나타냅니다.
- 사용자명과 그룹명: 파일이나 디렉토리의 소유자와 그룹을 나타냅니다.
- 파일 크기: 파일의 크기를 바이트 단위로 표시합니다.
- 생성일자: 파일이나 디렉토리의 최종 수정 날짜와 시간을 나타냅니다.
- 파일명: 파일이나 디렉토리의 이름을 표시합니다.
- 파일 타입: 각 항목의 첫 글자는 파일의 타입을 나타냅니다.
- head & tail: 파일의 첫 10줄(head)과 마지막 10줄(tail)을 출력합니다.
- tail -f(follow) : continuously watch logs
- grep [-option] patternToSearch [directory] : global regular expression print, 파일이나 입력 스트림에서 특정 패턴과 일치하는 라인을 찾아 출력합니다. 다양한 옵션을 사용할 수 있습니다:
- -i (ignore case): 대소문자를 구분하지 않고 검색합니다.
- -v (invert match): 지정한 패턴을 포함하지 않는 라인을 출력합니다.
- -n (line number): 검색 결과에 라인 번호를 추가합니다.
- -l (list): 패턴과 일치하는 파일명만 출력합니다.
- -c (count): 패턴과 일치하는 라인의 수만 출력합니다.
- -r (recursive): 하위 디렉토리까지 검색합니다.
- find [path] [options] [expression] : 지정한 경로에서 주어진 조건에 맞는 파일이나 디렉토리를 찾아내는 데 사용됩니다. 다양한 옵션으로 검색 조건을 세부적으로 설정할 수 있습니다
- -name: 특정 이름을 가진 파일을 찾습니다.
- -type: 파일 타입을 기준으로 검색합니다 (예: f는 일반 파일, d는 디렉토리).
- 하드링크&소프트링크
- cp [-rf] [filecopied] [newfile/path]: 파일을 복사함
- ln targetFile fileName (하드링크) : 파일원본과 동일한 자격의 개체가 생겨 원본파일이 삭제되어도 원본 역할을 함. file 하드링크파일 역시 엔트리가 inode를 가리켜서 inode를 가리키는 파일엔트리가 2개가 되는 격.
- ln [-s] targetFile fileName (소프트링크) : 윈도우의 바로가기와 동일한 개념으로 원본파일이 삭제되면 원본파일을 찾을 수 없음. 소프트링크파일 엔트리는 별도의 inode를 만들고 해당 Inode는 원본 파일엔트리를 가리켜서 바로가기 파일과 동일한 역할을 함.
파일압축/파일압출해제
- tar -czvf archive-name.tar.gz file1 file2 file3
- -c → Create archive
- -z → Compress with gzip
- -v → Verbose (shows progress)
- -f → Output filename
- tar -xvzf file.tgz : tar파일 압축해제ㅇ
- unzip package.zip : zip파일 압축해제
프로세스 관리
- - 포그라운드 프로세스 : 쉘에서 해당 명령을 실행한 후, 해당 프로세스 수행 종료까지 사용자가 다른 입력을 하지 못하게하는 프로세스. 특별한 커맨드를 넣지 않으면 기본으로 포그라운드 프로세스로 실행된다.
- - ctrl+c : 포그라운드 프로세스 취소
- - 백그라운드 프로세스 : 사용자 입력과 관계없이 실행되는 프로세스로 맨뒤에 &를 붙여줌. 특히, 시간이 오래걸리는 작업에 많이 사용됨. [작업번호] processID로 표기된다.
- - jobs : shell 에서 실행되고 있는 명령어 중 백그라운드 프로세스의 작업에 대한 정보를 확인
- - fg %number : job number을 백그라운드 프로세스를 포그라운드로 변경함
- ps [option] : process status 현재의 자기유저가 실행한 프로세스 출력
- 옵션
- -e (everyone, 모든 사용자의 프로세스) : Show every process running on the system", not just your own.
- -f (모든 정보 출력) : Use full-format output — shows more columns, including the full command line
- -a(all) : "Show processes associated with terminals (TTYs), except session leaders.
- -u (useroriented): 누가 프로세스의 소유자인지 정보도
- -x (expand) : 터미널로 실행되는 프로세스 외의 모든 프로세스를 보여줌, 데몬프로세스(24시간 계속켜져있는) 등등
- -l (long): 프로세스 관련 상세정보도
- 자주쓰이는 조합
- ps -ef : 트리구조로
- ps -aux : 현재실행중인 모든 프로세스와 정보 출력
- 정보 : (stat : running,stop, idle(커널용 쓰레드) time : cpu 사용시간 ; command : 프로세스실행명령 등
- 옵션
- -- 출력정보의 내용은 man ps 한후 원하는 정보는 /string 그리고 n을 누르면 문자열찾기로 정보확인가능
- kill [-9(option : 무조건)] [%작업번호 or PID] : 프로세스 종료시키는 명령어.
- $! : PID of the most recent background command
VI에디터
윈도우에서 작성한 파일과 리눅스에서 작성한 스크립트가 호환성이 다르기때문에 vi에서 작성하는 것을 권장함
- vi 'filename': vi 에디터로 파일을 열거나 새 파일을 생성합니다.
- :w 저장
- :q 종료
- :wq 저장 후 종료
- /word 아래방향으로 'word검색
- :set ff : show file format
- :set ff=unix / dos로 되어있다면 unix로 변경필요
쉘 스크립트 자바로 생성
일반적으로 CLI에서는 bash shell에 들어가 있기때문에 쉘 문법을 사용해도 자동적으로 parsing을 통해서 해석을 해준다.
그러나 java에서는 shell을 거치지 않고 process를 바로 생성하는 방식이므로, 아래와 같은 복잡도가 있는 shell을 생성하기 위해서는 shell을 직접적으로 호출해야한다.
Shell의 기능 및 역할
- && (run the second command only if the first succeeds)
- | (pipe)
- >, >> (redirection)
- $(...) (command substitution)
- Wildcards like *.txt
- Uses awk
- Has embedded quoting
Shell 호출
- /bin/sh "echo Hello World" : 'echo Hello World'라는 이름의 쉘 스크립트 파일을 실행함
- /bin/sh -c "ech Hello World" : 'echo Hello World'를 커맨드로 이해하고 커맨드를 실행한다.
Java Process Object
- Process is an object that represents an OS-level process started by your Java code.
process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd.toString()});
- Process create : Runtime.getRuntime().exec()
Method | Accepts | Use case |
exec(String) | One string | Simple commands (no shell logic) |
exec(String[]) | String array (command + args) | Commands with args or shell logic |
- Process object Control
Method | Purpose |
process.getInputStream() | Read the process's standard output (stdout) |
process.getErrorStream() | Read the process's error output (stderr) |
process.getOutputStream() | Write to the process's input (stdin) |
process.waitFor() | Wait for the process to finish |
process.exitValue() | Get the process's exit code |
process.destroy() | Kill (terminate) the process |
'개발기술 > 빌드, 배포, 운영' 카테고리의 다른 글
원격제어 (0) | 2025.03.13 |
---|---|
Jenkins CI/CD 자동화 (0) | 2025.01.26 |
Gradle 빌드 사용법 (0) | 2025.01.02 |
빌드와 Gradle 개념 (0) | 2024.11.12 |
빌드 파일 서버 배포 (0) | 2024.11.12 |