HyunsooZo's TIL logo HyunsooZo's TIL

Linux의 셸(Shell)

셸(Shell) 의미
bash Bourne-Again Shell
sh Bourne Shell
csh C Shell
ksh Korn Shell

사용자와 그룹

1. 사용자 추가하기

$ useradd userid

2. 사용자 조회하기

$ cat /etc/passwd
-> userid:x:1002:1002::/hom/userid:bin/sh
 #[사용자명]:[비밀번호]:[uid]:[gid]:[계정설명]:[홈dir]:[sh]

3. 그룹 조회

$cat /etc/group

4. 그룹 추가

$groupadd new_group

5. 그룹에 신규사용자 추가

$useradd -g [gid] [username]

6. 현재 작업자계정 확인

$whoami

7. 사용자전환하기

$su -           #root사용자로 전환
$su [username]  #[username]으로 전환

권한(Authority)

기본적으로 권한은 세 부분으로 표시

FileType+(소유자 권한) + (그룹 권한) + (기타 사용자 권한)

d : directory
l : link

1. Linux에서의 표현

권한 문자 파일인 경우 폴더인 경우
읽기 r 읽기 및 복사 가능 ls 명령어 사용 가능
쓰기 w 수정 가능 파일 생성 가능
실행 x 실행 가능 cd 명령어 사용 가능
없음 - 없음 없음

2. 권한 수준

권한 수준 표기 코드
읽기 2^2 = ‘4’  
쓰기 2^1 = ‘2’  
실행 2^0 = ‘1’  
권한없음  
–x 실행만 1
-w- 쓰기만 2
-wx 쓰기/실행 3
r– 읽기만 4
r-x 읽기/실행 5
rw- 읽기/쓰기 6
rwx 읽기/쓰기/실행 7

3. 권한부여 예시

chmod : 권한부여

$ chmod -R 755 file -> rwx/r-x/r-x
$ chmod -R 644 dir -> rw-/r--/r--
$ chmod -R 510 file -> r-x/--x/---

chown : 소유권 변경

$ chown user:group temp.txt
$ chown -R user:group mydir
권한 수준 코드
rwxrwxrwx 777
r-xr-rxr-x 555
r——— 400
rwx——- 700

Linux의 기본 명령어

명령어 사용법
sudo 명령어에 관리자 권한 부여
man 매뉴얼 확인
whoami 현재 로그인한 사용자 ID 확인
apt-get update 프로그램 업데이트(관리자 권한)
pwd 현재 디렉토리 경로 확인
cd 특정 디렉토리로 이동
  cd .. > 이전 디렉토리로 이동
  cd ~ > 홈 디렉토리로 이동
  cd /상위디렉토리/하위디렉토리 > 상위 디렉토리의 하위 디렉토리로 이동
ls 디렉토리 내용 리스트
  ls -al > “모든” 디렉토리 리스트
chmod 권한 설정
cat 파일 내용 표시
rm (파일명) 파일 또는 디렉토리 삭제
  rm -rf 디렉토리명 > 디렉토리 및 하위 디렉토리 삭제
vi 파일 생성 또는 편집
mkdir 디렉토리 생성
ps 일반적으로 사용되는 [ps -aux]
ps -a 모든 사용자의 프로세스 출력
ps -u 프로세스를 소유한 사용자의 상세 정보 출력
ps -l 프로세스의 상세 정보 출력
ps -x 모든 프로세스 출력(로그인 이후에 실행되지 않은 프로세스 포함)
ps -e 프로세스 정보 및 관련 환경 변수 출력
ps -f 관계 정보 출력
kill kill -9 프로세스명
cp a b ‘a’ 파일을 ‘b’로 복사
cp -rf a b ‘a’를 ‘b’로 복사(하위 디렉토리 포함)
mv file1 file2 file1을 file2로 이름변경
mv file1 .. fileN dir 여러 파일을 dir로 이동
touch 빈 파일 생성(이미 파일명 존재 시 마지막 수정날짜 업데이트)
grep 표현과 일치하는 입력 스트림의 라인 출력
head 파일 내용의 앞부분 확인 (디폴트 10줄)
tail 파일의 끝 부분만 확인
wc 파일의 행이나 단어 수 출력
(pipe) 명령어 조합 및 연결(주로 grep에 자주 쓰임..)

MacOs에서 Linux에 접속하기(1)

1. Terminal에서 .pem 파일 열기(파일이 위치한 경로에서)

chmod 400 bzhs1992.pem

2. ssh -i (pem 파일명.pem) Instance@elastic ip 입력

ssh = Secured Access

ssh -i bzhs1992.pem ubuntu@3.37.241.135

3. “yes”를 입력하여 연결

1.135
The authenticity of host '3.37.241.135 (3.37.241.135)' can't be established.
ED25519 key fingerprint is SHA256:dk6Puy97IkTH/oT6PtO3T31+Y2Goo6KdYJcxMRTxxtE.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes

MacOs에서 Linux에 접속하기(2)

1. Docker 설치

2. 리눅스(우분투) 이미지 풀링

hyunsoojo@HYUNSOOui-MacBook-Pro:~$docker image pull ubuntu

3.sdf 리눅스(우분투) 실행

hyunsoojo@HYUNSOOui-MacBook-Pro:~$docker run -it --name test-ubuntu ubuntu:latest /bin/bash

Standard Stream

1. Stream

2. Rediretion ( > < 사용)

ls > temp.txt     # ls output will be contained in `temp.txt` (cover)
ls >> temp.txt    # ls output will be added in `temp.txt` (adding)
head < temp.txt   # first 10 lines of `temp.txt` will be printed at the consol 

3. Pipe

ls | grep files.txt   # to know if `files.txt` exists in the ls list

4. grep cmd ?

grep [-option][patten][file or dir name]

Options  
-i Case insensitive
-v Print line w/o pattern
-n Put Seq No for every single files
-l Print only file names
-c Print the number of Lines which pattern match
-r Print until subdirectory

Process vs Binary

1. Code Image / Binary : 실행 파일

2. Process : 실행중인 프로그램

Process includes..

- Virtual Memory or Physical Memory - System Resource - Schedule unit

Foreground/Background Process

Foreground Process

사용자 입력이 필요한 프로세스로, foreground에서 실행.
쉘은 프로세스가 완료될 때까지 사용자의 새로운 입력을 받지 않음.

Background Process

사용자 입력과는 독립적으로 실행되는 프로세스. 쉘은 프로세스가 완료되기를 기다리지 않고
사용자는 프로세스가 백그라운드에서 실행되는 동안 명령을 계속 입력할 수 있음.

Example of Background process:

$ find / -name '*.py' > /home/ubuntu/list.txt &  #put & at the end 
# checking current background process running
$ jobs               

Example of foreground process :

$ fg [bg index]    #change background process into foreground process

Ubuntu package management

$ sudo apt-get update
$ sudo apt-get install [package name]
$ sudo apt-get remove [package name]
$ sudo apt-get --purge [package name] # delete including Setting file

Shell Script

셸에서 돌아가도록 작성된 스크립트 (*.sh)

Shebang

#!/bin/bash 

Echo

echo "somthing.." 

Variable

NAME=`LINUX`
COUNT=10

echo $NAME

java -jar $NAME-$COUNT.jar

# LINUX-10.jar 파일이 실행됨. 

$ : 사전정의 변수

echo $$     #shell pid
echo $0     #shell script file name
echo $1-$9  #shell parameter
echo $#     #shell parameter count
echo $?     #exit code

예약변수 (권장되지는 않음)

echo $HOME  # home directory
echo $PATH  # file path
echo $USER  # user account 

PATH-/any/where  #->!!warning!!

if : 조건문

if[condition]
then 
    # do smth
else
    # do smth
fi

#####예시######

#!/bin/sh

VAR="HELLO"

if[ -z "$VAR" ]; then
    echo "NULL"
else
    echo "$VAR is not null"
fi

for 반복문

 #!/bin/sh

 for VAR in LIST
 do
    #do smth
 done

#####for 예시######

#!/bin/sh

for f in $(ls)
do
    echo $f
done
TOP