🚀 缺失的 Shell 脚本速成课程
Bash是一种Shell和命令语言。您可以像使用其他语言一样使用它来编写脚本。Bash 脚本可以在 Linux 和 Mac 上直接运行。对于 Windows,需要进行一些简单的练习。在本教程中,我将讲解Shell 语法,而不是Shell 命令,例如ls
、grep
、cat
。
本速成课程将教您编写 shell 脚本所需的所有必要知识。
1. 你好,世界
本教程只需要一个终端和一个文本编辑器。让我们用 Bash 编写一个简单的 Hello World。创建一个名为“hello world”的新文件script.sh
,并写入以下代码:
#!/bin/bash
echo "Hello World"
现在保存此文件。要使其可执行,请在终端中运行。然后,你就可以在终端中chmod +x ./script.sh
运行上述脚本了。./script.sh
Hello World
太棒了!你的第一个 Bash 脚本!让我们仔细看看这段代码。第一行#!/bin/bash
叫做“ shebang”。它告诉你的计算机应该让哪个程序运行这段代码。在我们的例子中,它就是“ shebang /bin/bash
”。
如果你想用JavaScript而不是Bash,可以这样写。
#!/bin/node
console.log("Hello Javascript")'
$ ./script.sh
Hello Javascript
上述代码仅在目录中安装了 Node 的情况下有效/bin/
。因此,实际上您可以使用任何语言编写代码。您只需指定哪个程序可以处理该代码,系统就会将该文件传递给该程序。
现在让我们回到 Bash。在上面的代码中,第二行是echo "Hello World"
. ,echo
它是一个将内容打印到标准输出(在本例中是终端)的命令。
2.变量
我们稍微修改一下上面的代码。
#!/bin/bash
name="Bash"
echo "Hello, $name"
$ ./script.sh
Hello, Bash
我们创建一个名为 的变量name
,并将字符串存储"Bash"
到其中。然后,要访问它,我们需要使用 来引用它$
。如果您忘记了$
符号,bash 会将其视为name
字符串字面量,而您将获得Hello name
的输出。
=
注意,定义变量时,前后不要有空格。引用时,请使用双引号。
3.用户输入
让我们继续修改脚本。我们将请求用户输入他们的姓名,然后回复他们。
#!/bin/bash
read -p "What is you name: " name
echo "Hello $name"
$ ./script.sh
What is you name: godcrampy
Hello godcrampy
该命令从标准输入read
中获取一行输入并将其保存到变量 中。该标志允许我们在接收输入之前传递 的提示。name
-p
"What is your name: "
在字符串中引用变量的一个巧妙技巧是使用花括号:
#!/bin/bash
read -p "Enter an action: " verb
echo "You are ${verb}ing"
$ ./script.sh
Enter an action: cook
You are cooking
4. 评论
# Comments start with hash
多行注释有点复杂。
5. 论点
$1
$2
等,存储传递到脚本中的参数。存储$0
文件名。
#!/bin/bash
echo $0
echo $1
echo $2
echo "${@}" # Access all the arguments [More on this later]
$ ./script.sh first second
./script.sh
first
second
first second
6. 表达式
常见的表达式有三种:返回值、算术求值和test
命令。这三种表达式都返回真或假。
返回值这
实际上是诸如 等程序的返回值grep
。find
算术求值
Bash 使用括号来表示算术表达式。
例如:(( 1 <= 5))
Test
命令
命令test
通常用[
或表示,[[
可以执行更复杂的操作:
[[ -e "$file" ]] # True if file exists
[[ -d "$file" ]] # True if file exists and is a directory
[[ -f "$file" ]] # True if file exists and is a regular file
[[ -z "$str" ]] # True if string is of length zero
[[ -n "$str" ]] # True is string is not of length zero
# Compare Strings
[[ "$str1" == "$str2" ]]
[[ "$str1" != "$str2" ]]
# Integer Comparisions
[[ "$int1" -eq "$int2" ]] # $int1 == $int2
[[ "$int1" -ne "$int2" ]] # $int1 != $int2
[[ "$int1" -gt "$int2" ]] # $int1 > $int2
[[ "$int1" -lt "$int2" ]] # $int1 < $int2
[[ "$int1" -ge "$int2" ]] # $int1 >= $int2
[[ "$int1" -le "$int2" ]] # $int1 <= $int2
请注意,这[
实际上是一个命令。尝试运行$ where [
. test
,[
并且[[
它们几乎相似。但有一些细微的差别。
和与或
[[ ... ]] && [[ ... ]] # And
[[ ... ]] || [[ ... ]] # Or
7. 条件语句
既然我们知道了表达式,我们就可以在条件语句中使用它们。
# 1. Return values
# If notes.md file doesn't exist, create one and
# add the text "created by bash"
if find notes.md
then
echo "notes.md file already exists"
else
echo "created by bash" | cat >> notes.md
fi
# 2. Arithmetic Evaluations
read -p "Enter your age: " age
if (( "$age" > 18 ))
then
echo "Adult!"
elif (( "$age" > 12 ))
then
echo "Teen!"
else
echo "Kid"
fi
# 3. Test Expressions
# Check if argument was passed
# "$1" corresponds to first argument
if [[ -n "$1" ]]
then
echo "Your first argument was $1"
else
echo "No Arguments passed"
fi
该if
语句必须以 结尾fi
。
如果你足够敏锐,你可能会想知道为什么我使用"$var"
和 而不是来引用变量。答案$var
如下。(提示:两种方法都可以,但使用双引号更安全)。
8.循环
# print numbers 1 to 10
# c like for loop
for (( i = 1; i <= 10; ++i ))
do
echo "$i"
done
# for in
for i in {1..10}
do
echo "$i"
done
# while
i=1
while [[ "$i" -le 10 ]]
do
echo "$i"
((i++))
done
# until
i=1
until [[ "$i" -eq 11 ]]
do
echo "unitl $i"
((i++))
done
数组迭代
数组使用括号声明,元素之间不带逗号。稍后会详细介绍数组。
arr=(a b c d)
# For in
for i in "${arr[@]}"
do
echo "$i"
done
# c like for
for (( i = 0; i < "${#arr[@]}"; i++))
do
echo "${arr[$i]}"
done
# while
i=0
while [[ "$i" -le "${#arr[@]}" ]]
do
echo "${arr[$i]}"
(( i++ ))
done
${arr[@]}
允许您迭代数组同时${#arr[@]}
返回数组的长度。
迭代参数@
保存传递给脚本的所有参数
for i in "$@"
do
echo "$i"
done
continue
并break
以与其他编程语言相同的方式工作。continue
跳过当前迭代。break
退出循环。
9.数组
bash 中的数组用括号定义,元素之间没有逗号分隔。
arr=(a b c d)
读
echo "${arr[1]}" # Single element
echo "${arr[-1]}" # Last element
echo "${arr[@]:1}" # Elements from 1
echo "${arr[@]:1:3}" # Elements from 1 to 3
插入
arr[5]=e # direct address and insert/update
arr=(${arr[@]:0:1} new ${arr[@]:1}) # Adding 'new' to array
删除
arr=(a b c d)
unset arr[1]
echo << "${arr[1]}" # Outputs nothing
注意,一旦我们删除位置 1 的元素,后面的元素就不会占据它的位置。删除完成后,我们需要重新索引数组。
arr=(a b c d)
unset arr[1]
arr=("${arr[@]}")
echo << "${arr[1]}" # c
10. 功能
Bash中的函数语法与其他编程语言类似。函数的参数访问方式与脚本的参数访问方式相同。
greet() {
echo "Hello, $1"
}
greet Bash # Hello, Bash
函数定义没有指定任何传递给它的参数信息。注意,在调用函数时,不使用括号。而是用空格分隔参数。
可以使用 访问函数的所有参数@
。
greet() {
echo "Hello, ${@}"
}
greet every single body # Hello, every single body
本次速成课程就到这里。现在你可以开始编写自己的 Shell 脚本了。除了我这里提到的内容之外,还有更多值得探索的内容。
🌟 我制作了一些备忘单🚀 在Instagram | Github | Twitter |网站
上找到我 😄 祝你有美好的一天!