오픈 소스 수업의 과제로 코드카데미(https://www.codecademy.com/learn)의 Learn the Command Line를 수강하며 리눅스 명령어를 정리해 보았다.
ls
현재 위치의 폴더 및 파일을 리스트로 나타내줌
pwd
print working directory
현재 위치의 경로 출력
cd [ ]
change the directory
[ ]로 이동
이동한 후에 pwd로 확인해보자
cd ..
상위 폴더로 이동
cd ../[ ]
현재 위치의 [ ]로 이동
mkdir [ ]
[ ]라는 경로(폴더) 만들기
ls로 확인
touch [ ].확장자
현재 경로에 [ ].확장자 파일을 만듦
Generalizations
The command line is a text interface for the computer’s operating system. To access the command line, we use the terminal.
A filesystem organizes a computer’s files and directories into a tree structure. It starts with the root directory. Each parent directory can contain more child directories and files.
From the command line, you can navigate through files and folders on your computer:
pwd
outputs the name of the current working directory.ls
lists all files and directories in the working directory.cd
switches you into the directory you specify.mkdir
creates a new directory in the working directory.touch
creates a new file inside the working directory.
Viewing and Changing the File System
ls의 옵션들
-a: 숨김 파일과 디렉토리 보여줌(모든 파일)
앞에 .붙은 게 숨김 파일
-l: long format으로 모든 콘텐츠 보여줌
접근 권한
부모 링크와 현재 링크 포함한 자식 디렉토리와 파일 수
유저네임
파일 사이즈(bytes)
마지막으로 수정된 시간
파일 혹은 디렉토리 이름
-t: 마지막 수정된 기준으로 정렬해서 보여줌
-alt: 멀티 옵션(쓰까)
cp [ ] { }
[ ]의 내용을 { }에 복사
Wildcards
cp * satire/: 현재 디렉토리의 모든 파일 선택하여 satire/로 복사
[ ]*.{ }: 현재 디렉토리의 [ ]으로 시작하고 .{ }로 끝나는 모든 파일들을 scifi/로 복사
mv
mv [파일] [디렉토리]: 파일을 디렉토리로 이동
mv [파일1] [파일2] [디렉토리]: 복수의 파일 이동
mv [파일1] [파일2]: [파일1]을 [파일2]로 이름 바꿈
rm
rm [ ]: [ ]라는 파일을 삭제
rm -r [ ]: [ ]라는 디렉토리와 [ ]의 모든 하위 디렉토리 삭제
rm은 영구 삭제하므로 주의하자.
Generlizataion
Options modify the behavior of commands:
ls -a
lists all contents of a directory, including hidden files and directoriesls -l
lists all contents in long formatls -t
orders files and directories by the time they were last modifiedMultiple options can be used together, like
ls -alt
From the command line, you can also copy, move, and remove files and directories:
cp
copies filesmv
moves and renames filesrm
removes filesrm -r
removes directories
Wildcards are useful for selecting groups of files and directories
Redirecting Input and output
stdin
standard input
echo "Hello" 입력
Hello 출력
echo "Hello" > hello.txt 입력
hello.txt에 Hello 입력
stdout
standard output
cat hello.txt Hello 출력
stderr
standard error
: 프로세스가 실패했을 때
cat [stdout] > {file}
file에 있는 기존의 모든 내용을 stdout으로 덮어씌워버림.
Q. cat A > B과 cp A B의 차이는?
https://unix.stackexchange.com/questions/30295/cp-vs-cat-to-copy-a-file
참고하여 작성
cat은 밀도가 낮은 파일을 확장한다. 갭을 거의 0바이트로 채우면서
cp는 구멍을 보존
cat이 속도가 더 빠르다.
cat은 라이브러리도 얼마 안 쓰고 파일 오픈도 얼마 안 하며 바로 stream으로 보냄
반면 cp는 cat보다 많은 라이브러리를 읽고 파일이 없으면 생성하는 등 system call이 상대적으로 많다
cat [stdout] >> {file}
stdout에 있는 내용들을 file에 append(add)
cat < [file]
[file]이 cat의 표준 입력이 됨
표준 출력은 터미널 안에 나타남
Q. 그냥 cat이랑은 뭔 차이?
https://unix.stackexchange.com/questions/258931/difference-between-cat-and-cat
참고하여 작성
cat: 파일 오픈
cat < : 파일 오픈하고 cat 표준 입력으로 전달
cat [file] | wc
|: pipe, 명령어에서 명령어 redirection(여러 개 쓸 수 있게 해준다는 말인 듯) 명령어들을 연결(chain)시켜줌
wc: 파일 안에 있는 줄 수, 단어 수, 문자 수를 출력하는 명령어
sort
표준 입력을 받아 알파벳 순으로 정렬해 표준 출력
cat lakes.txt | sort > sorted-lakes.txt 와 같이 사용
cat lakes.txt | sort
uniq
인접한데 똑같은 줄을 필터링
똑같은 내용이더라도 인접해있지 않으면 필터링하지 않음
sort deserts.txt | uniq > uniq-deserts.txt 와 같이 쓸 수 있음
grep
global regular expression print
grep Mount mountains.txt : mountains.txt 파일 안의 Mount가 포함된 줄을 탐색
grep -i Mount mountains.txt
: Mount와 mount 모두 찾음(i=inintensive, 대문자와 소문자 모두 찾음)
grep -R [문자열] {디렉토리}
: R은 recursive. 디렉토리 안의 모든 파일들을 탐색해서 매치된 결과값과 함께 파일이름과 줄을 출력
grep -Rl [문자열] {디렉토리}
: -R과 기능은 동일하나 파일이름만을 출력
sed
stream editor: 표준 입력 받고 데이터를 출력하기 전에 expression에 따라 수정. find and replace와 유사하다
sed 's/[찾을 문자열]/[대체할 문자열]/g' [파일이름]
s: substitution. sed 쓸 때 항상 쓰임
g: global. 모든 해당하는 문자열을 바꾸는 건데 g를 안 쓰면 각 줄에서 첫번째로 걸리는 문자열만 바꿈
Generalizations
Congratulations! You learned how to use the command line to redirect standard input and standard output. What can we generalize so far?
Redirection reroutes standard input, standard output, and standard error.
The common redirection commands are:
>
redirects standard output of a command to a file, overwriting previous content.>>
redirects standard output of a command to a file, appending new content to old content.<
redirects standard input to a command.|
redirects standard output of a command to another command.
A number of other commands are powerful when combined with redirection commands:
sort
: sorts lines of text alphabetically.uniq
: filters duplicate, adjacent lines of text.grep
: searches for a text pattern and outputs it.sed
: searches for a text pattern, modifies it, and outputs it.
Configuring the Environment
nano [파일이름]
nano 텍스트 에디터 안에서 파일이름에 해당하는 파일 오픈
문자열 나노에 입력
Ctrl+
O: output. 파일 저장
X: exit. 나노 프로그램에서 나감
G: help menu를 연다
clear: 터미널 윈도우 클리어하고 명령 프롬프트를 화면 맨 위로 옮긴다
~/.bash_profile
환경 설정을 저장하기 위해 쓰이는 파일 이름
보통 bash profile이라고 함
세션이 시작되면 명령어를 실행하기 전에 bash profile의 내용을 로드한다
nano ~/.bash_profile: ~/.bash_profile이라는 파일 생성
~: 유저의 home directory
.: hidden file
~/.bash_profile은 커맨드라인이 bash profile을 인식하는 방법이기 때문에 중요하다
alias
자주 쓰이는 명령어의 단축키(keyboard shortcuts)나 별명(alias) 생성
alias 생성 뒤에는 source ~/.bash_profile 을 통해 별명 사용 가능하다
alias pd="pwd": pwd 커맨드의 별명(pd) 생성
alias hy="history", alias ll="ls -la" 등
Environment Variables(환경 변수)
명령어와 프로그램을 넘나들고 환경에 대한 정보를 저장하는 변수
USER="유저명"
export: 현재 세션의 모든 하위 세션을 가능하도록 하는 변수로 프로그램에 변수가 실행되도록 함
echo $[변수명]
$는 변수값을 반환할 때 사용
PS1
명령 프롬프트의 구조(makeup)와 양식(style)을 정의하는 변수
export PS1=">> ": 명령 프롬프트의 변수를 설정하고 내보냄
여기에서는 $를 >> 로 바꿈(줄마다 앞에 붙는 $가 바뀐 것)
source 커맨드 사용 후 새로운 명령 프롬프트를 사용할 수 있다
HOME
home directory의 path를 보여주는 환경 변수
echo $HOME: home directory path 출력
HOME 변수를 바꿀 수 있지만 대부분의 경우에 필수는 아니다
PATH
스크립트를 포함한 디렉토리를 담은 리스트들
디렉토리의 리스트를 저장하는 환경 변수로 디렉토리는 콜론(:)으로 구분되어 있다
각 디렉토리는 실행될 수 있는 커맨드라인이 담긴 스크립트들을 포함하고 있다
/bin/pwd 를 쳤을 때 실행되는 스크립트 : /home/ccuser/workspace/music
/bin/ls 를 쳤을 때 실행되는 스크립트
: artists
PATH에 스크립트를 추가할 수도 있다
env
environment
현재 유저의 환경 변수의 리스트를 반환한다
env | grep PATH: 단일(로 실행되는) 환경 변수값value of a single environment variable을 보여주는 명령어
grep이 변수 PATH의 값을 탐색해서 터미널에 출력한다
Generalizations
Congratulations! You learned to use the bash profile to configure the environment. What can we generalize so far?
The environment refers to the preferences and settings of the current user.
The nano editor is a command line text editor used to configure the environment.
~/.bash_profile is where environment settings are stored. You can edit this file with nano.
environment variables are variables that can be used across commands and programs and hold information about the environment.
export VARIABLE="Value"
sets and exports an environment variable.USER
is the name of the current user.PS1
is the command prompt.HOME
is the home directory. It is usually not customized.PATH
returns a colon separated list of file paths. It is customized in advanced cases.env
returns a list of environment variables.
Bash Scripting
Bash(혹은 shell) scripting은 반복되는 작업을 자동화하고 개발 시간을 줄여준다.
Bash scripts는 Bash shell 인터프리터 터미널 안에서 실행된다.
터미널에서 실행할 수 있는 모든 명령어를 Bash script에서 실행할 수 있다.
자주 사용할 명령어들이 있다면 Bash script에 쓸 수 있다.
컴퓨터가 Bash scripts를 실행시킬 때
script.sh의 맨 첫줄에 #!/bin/bash입력
#!/bin/bash: script에 무슨 인터프리터를 쓸지 컴퓨터에게 알려줌
자주 사용되는 스크립트는 ~/bin/에 저장하는 것이 좋다.
Variables
bash scripts 안에서 [변수명]=값으로 선언
greeting="Hello"
변수값에 접근하려면 $greeting과 같이 접두에 붙여야함
echo $greeting: greeting이라는 변수의 값을 프린트
script.sh
#!/bin/bash
phrase="Hello to you!"
echo $phrase
bash
./script.sh
(로 실행)
Conditionals
스크립트에서 조건문 사용 가능
대괄호 앞 뒤에 공백이 있어야 제대로 작동
if [ 조건 ]
then
실행문1
else
실행문2
fi
Equal:
-eq
Not equal:
-ne
Less than or equal:
-le
Less than:
-lt
Greater than or equal:
-ge
Greater than:
-gt
Is null:
-z
Q. 왜 script에서는 부등호를 쓰지 않나?
Equal:
==
Not equal:
!=
문자열 비교
if ["$foo"=="$bar"]
Loops
for, while, until 세 가지의 반복문이 있음
for word in $paragraph
do
echo $word
done
for문 맨 위의 word에는 $이 붙지 않고, 실행문에만 붙음
while은 조건문이 참일 동안 실행되고 until은 조건문이 참이 될 때까지 실행됨
while [$index -lt 5]
do
echo $index
index=$((index+1))
done
until [$index -eq 5]
do
echo $index
index=$((index+1))
done
bash에서는 대수 연산에 $((...))을 쓴다. 대수 연산 안에서의 변수에는 $ 안 붙임
Inputs
bash에서 외부 파일에 접근
read: 유저 입력에 접근하여 변수에 저장
echo "Guess a number"
read number
echo "You guessed $number"
$@: 유한한 숫자만큼 반복하고 싶을 때
for color in "$@"
do
echo $color
done
*: 디렉토리의 모든 파일을 가져오고 싶을 때
files=/some/directory/*
모든 파일의 path와 파일명에 접근
for file in $files
do
echo $file
done
Aliases
.bashrc나 .bash_profile 파일에 alias 설정 가능
saycolors.sh를 saycolors로
alias saycolors='./saycolors.sh'
saycolors의 첫번째 입력에 "green"이 포함되게 하고 싶으면
alias saycolors='./saycolors.sh "green"'
greet3이라는 alias 만들기
터미널에서 nano ~/.bashrc
alias greet3="./script.sh [숫자]" 추가
저장 후 source ~/.bashrc
greet3로 실행해보기
Review
Take a minute to review what you’ve learned about bash scripting.
Any command that can be run in the terminal can be run in a bash script.
Variables are assigned using an equals sign with no space (
greeting="hello"
).Variables are accessed using a dollar sign (
echo $greeting
).Conditionals use
if
,then
,else
,fi
syntax.Three types of loops can be used:
for
,while
, anduntil
.Bash scripts use a unique set of comparison operators:
Equal:
-eq
Not equal:
-ne
Less than or equal:
-le
Less than:
-lt
Greater than or equal:
-ge
Greater than:
-gt
Is null:
-z
Input arguments can be passed to a bash script after the script name, separated by spaces (myScript.sh “hello” “how are you”).
Input can be requested from the script user with the
read
keyword.Aliases can be created in the
.bashrc
or.bash_profile
using thealias
'tip' 카테고리의 다른 글
cuda v10.1 getDevice() 오류 해결하기 (0) | 2020.04.15 |
---|---|
로컬 저장소 깃헙에 만든 저장소로 푸시할 때 생기는 에러 해결 (0) | 2019.10.25 |
유용한 무료 이모티콘 사이트 flaticon (0) | 2019.02.15 |
jupyter notebook(주피터 노트북) 설치 및 실행하기 (1) | 2019.02.13 |
노트북 팬 소음 해결법 (1) | 2019.02.04 |
댓글