網絡的一部分
在27分鐘內學習bash腳本
這是受到5分鐘學習的學習啟發,在30分鐘內學習生鏽和曲折的半小時。
bash (再次是Bourne Shell)是在1989年開發的,它比C年輕,但可能比您習慣於開發的任何東西都要年齡。這並不使其過時或過時。 BASH幾乎無處不在:在UNIX/Linux , MacOS和Windows (WSL)上,它用於各種“現代”軟件(Docker,Deployment/build腳本,CI/CD),並且您將在不使用bash的情況下擁有豐富的開發人員職業的機會是準零。那為什麼不擅長呢?
每當您在終端/控制台中打字時,您都會在交互式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 ! bash變量未構圖。變量的值和/或上下文確定它是否將其解釋為整數,字符串或數組。
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具有最常見的“測試”程序(例如test -f output.txt ),該程序最常用於[[ -f output.txt ]] 。還有[ -f output.txt ]的較舊語法,但是雙方括號是優選的。該程序測試特定條件,如果滿足條件,則以0(“確定”)返回。此目的將在下一章中變得明確。
[[ -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。例如,“排序”是一個程序,該程序在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 :發生錯誤時停止腳本