네트워크의 일부
27 분 안에 Bash 스크립팅에 대해 알아보십시오
이것은 30 분 안에 Rust와 Zig를 배우기 위해 30 분 동안 Learn Go in ~ 5 분에서 영감을 얻었습니다.
bash (Bourne Again Shell)는 1989 년에 개발되었으며, 이는 C보다 젊지 만 개발하는 데 익숙한 것보다 나이가 많을 것입니다. 이것은 구식이거나 쓸모 없게 만들지 않습니다. Bash는 UNIX/Linux , MacOS 및 Windows (WSL)의 모든 곳에서 실질적으로 실행됩니다. 모든 종류의 '현대적인'소프트웨어 (Docker, Deployment/Build Scripts, CI/CD) 및 bash 사용하지 않고 풍부한 개발자 경력을 가질 가능성은 Quasi Zero입니다. 그렇다면 왜 그것을 잘하지 않습니까?
터미널/콘솔에 입력 할 때마다 대화식 bash 쉘 (또는 더 정교한 사촌 zsh 또는 fish )에 있습니다. ls , whoami , echo "hello" 와 같이 여기에 입력 할 수있는 모든 명령은 Bash 명령으로 자격이 있으며 스크립트에서 사용할 수 있습니다.
터미널에있는 동안 다음 명령을 입력하십시오 (복사하지 마십시오. 명령 줄의 시작을 표시합니다).
> touch myscript.sh # create the file 'myscript.sh' as an empty file좋아하는 텍스트 편집기 (Sublime/Vcode/JetBrains/...) 로이 새 파일을 편집하고 다음 2 줄을 추가하십시오.
#! /usr/bin/env bash
echo " Hello world! "이제 터미널로 돌아가서 타이핑하십시오
> chmod +x myscript.sh # make the file executable, so you can call it directly as ./myscript.sh
> ./myscript.sh # execute your new script
Hello world ! 배쉬 변수는 유형이 없습니다. 변수의 값 및/또는 컨텍스트는 정수, 문자열 또는 배열로 해석 될 것인지 결정합니다.
width=800 # variables are assigned with '='
name= " James Bond " # strings with spaces should be delimited by " or '
user_name1=jbond # variable names can contain letters, digits and '_', but cannot start with a digit
echo " Welcome $name ! " # variable are referenced with a $ prefix
file= " ${user} _ ${uniq} " # ${var} can be used to clearly delimit the name of the variable
echo " ${width :- 400} " # if variable $width is not set, the default 400 will be used
echo " ${text / etc / &} " # replace the 1st text 'etc' by '&' in the variable before printing it
echo " ${text // etc / &} " # replace all texts 'etc' by '&' in the variable before printing it
w= $(( width + 80 )) # $(()) allows arithmetic: + - / * %
input= $1 # $1, $2 ... are the 1st, 2nd ... parameters specified on the command line
input= " $1 " # put quotes around any variable that might contain " " (space), "t" (tab), "n" (new line)
script= $0 # $0 refers to the actual script's name, as called (so /full/path/script or ../src/script)
temp= " /tmp/ $$ .txt " # $$ is the id of this process and will be different each time the script runs
echo " $SECONDS secs " # there are preset variables that your shell sets automatically: $SECONDS, $HOME, $HOSTNAME, $PWD
LANG=C do_something # start the subcommand do_something but first set LANG to "C" only for that subcommand
script= $( basename " $0 " ) # execute what is between $( ) and use the output as the value Bash에는 [[ -f output.txt ]] 로 가장 일반적으로 사용되는 필수 '테스트'프로그램 (예 : test -f output.txt )이 있습니다. [ -f output.txt ] 의 구형 구문도 있지만 이중 사각형 괄호가 선호됩니다. 이 프로그램은 특정 조건을 테스트하고 조건이 충족 된 경우 0 ( 'OK')으로 반환합니다. 다음 장에서는 이것의 목적이 분명해질 것입니다.
[[ -f file.txt ]] # file exists
[[ ! -f file.txt ]] # file does not exist -- ! means 'not'
[[ -f a.txt && -f b.txt ]] # both files exist -- && means AND , || means OR
[[ -d ~ /.home ]] # folder exists
[[ -x program ]] # program exists and is executable
[[ -s file.txt ]] # file exists and has a size > 0
[[ -n " $text " ]] # variable $text is not empty
[[ -z " $text " ]] # variable $text is empty
[[ " $text " == " yes " ]] # variable $text == "yes"
[[ $width -eq 800 ]] # $width is the number 800
[[ $width -gt 800 ]] # $width is greater than 800
[[ file1 -nt file2 ]] # file1 is newer (more recently modified) than file2 if [[ ! -f " out.txt " ]] ; then # if ... then ... else ... fi
echo " OK "
else
echo " STOP "
fi
[[ -f " out.txt " ]] && echo " OK " || echo " STOP " # can also be written as 1 line if the 'then' part is 1 line only
while [[ ! -f output.txt ]] ; do # while ... do ... done
(...) # wait for output.txt
continue # return and do next iteration
done
for file in * .txt ; do # for ... in ... do ... done
echo " Process file $file "
(...)
done
for (( i = 0 ; i < n; i ++ )) ; do # for (...) do ... done
(...)
done
case $option in # case ... in ...) ;; esac
export) do_export " $1 " " $2 " # you might know this as a 'switch' statement
;;
refresh) do_refresh " $2 "
;;
* ) echo " Unknown option [ $option ] "
esac myfunction (){ # bash functions are defined with <name>(){...} and have to be defined before they are used
# $1 = input # functions can be called with their own parameters, and they are also referenced as $1 $2
# $2 = output # this means that the main program's $1,$2...parameters are no longer available inside the function
local error # a variable can be defined with local scope. if not, variables are always global
(...)
return 0 # this explicitly exits the function with a status code (0 = OK, > 0 = with an error)
}numbers=(1 2 3) # define array with all values
numbers[0]= " one " # replace 1st element (indexes start at 0) by "one"
echo ${numbers[@]} # [@] represents the whole array
numbers=( ${numbers[@]} 4) # add new element to array
${ # numbers[@]} # nb of elements in the array
for element in ${numbers[@]} ; do
...
done 각 스크립트, 함수, 프로그램에는 3 개의 기본 스트림 (파일 설명자)이 있습니다 : Stdin, Stdout 및 Stderr. 예를 들어 'Sort'는 stdin에서 텍스트 줄을 읽고 stdout에 정렬 된 출력이며 Stderr에서 발생하는 오류를 보여주는 프로그램입니다.
# by default, `stdin` is your interactive terminal, `stdout` and `stderr` are both your terminal
sort # stdin = read from terminal (just type and end with CTRL-D), stdout = terminal
< input.txt sort # stdin = read from input.txt, stdout = terminal
< input.txt sort > sorted.txt # stdin = read from input.txt, stdout = written to sorted.txt
< input.txt sort >> sorted.txt # stdin = read from input.txt, stdout = append to sorted.txt
< input.txt sort > /dev/null # stdin = read from input.txt, stdout = just ignore it, throw it away
echo " Output " # writes "Output" to stdout = terminal
echo " Output " >&2 # writes "Output" to stderr = terminal
program 2> /dev/null > output.txt # write stdout to output.txt, and ignore stderr
program & > /output.txt # redirect both stdout and stderr to output.txt
find . -name " *.txt "
| while read -r file ; do # while read is a good way to run some code for each line
output= " $( basename " $file " .txt ) .out "
[[ ! -f " $output " ]] && < " $file " sort > " $output "
done | (파이프) 캐릭터는 Bash의 초강대국입니다. 그것은 당신이 정교한 프로그램의 체인을 만들 수 있으며, 각 프로그램은 다음 stdout 을 다음 프로그램의 stdin 으로 전달합니다. UNIX 철학이 " 한 가지 일을하고 잘하는 프로그램 작성 "을 처방한다면, Bash는 모든 전문 프로그램을 함께 붙잡는 완벽한 도구입니다. 정렬을 정렬하고 sort 사용하고 검색하고 grep 사용하여 문자를 교체하고 tr 사용하십시오. 이 모든 것을 함께 묶으려면 Bash와 파이프를 사용하십시오.
ls | sort | head -1 # ls lists filenames to its stdout, which is 'piped' (connected) to sort's stdin.
# sort sends the sorted names to its stdout, which is piped to stdin of 'head -1'.
# head will just copy the first line from stdin to stdout and then stop
# the following chain will return the 5 most occurring non-comment lines in all .txt files
cat * .txt | grep -v ' ^# ' | sort | uniq -c | sort -nr | head -5
# this line gives a lowercase name for the current script (MyScript.sh -> myscript)
script_name= $( basename " $0 " .sh | tr " [:upper:] " " [:lower:] " ) ( # ( ... ) starts a new subshell with its own stdin/stdout
cat * .txt
curl -s https://host/archive.txt
) | sort
start_in_background & # start the program and return immediately, don't wait for it to end
git commit -a && git push # 'git push' will only execute if 'git commit -a' finished without errors set -uo pipefail : 오류가 발생하면 스크립트를 중지합니다.