5分钟学会Shell脚本
目录
- 入门
- 评论
- 变量
- 循环
- 条件
- 案件
- 函数
- 用户输入
- 算术
- 数组
- 调试 Shell 脚本
- 技巧和工具
入门
创建一个名为script的文本文件(扩展名为.sh,非必需),并将以下内容添加到该文件中。
#!/bin/bash
echo "Hello, World!"
您需要运行以下命令,使刚刚创建的 shell 脚本可执行:sudo chmod +x script.sh
现在你可以运行脚本,查看屏幕上打印的消息。source script.sh
Hello, world!
评论
与其他编程语言一样,你可以在脚本中添加注释来详细描述脚本的功能。Bash 脚本支持单行注释和多行注释。
单行注释
#!/bin/bash
# This is a single line comment
echo "Hello, world!"
多行注释
#!/bin/bash
: '
This is a multi-line comment
spanning not just one line
but many lines
'
echo "Hello, world!"
变量
Bash 中有两种类型的变量,
- 用户自定义变量:是由用户在 shell 脚本中定义的变量,通常全部为小写字母。
#!/bin/bash
message="Shell scripting tutorial"
echo $message
- Shell 定义的变量:是由 Bash shell 定义的变量,通常全部为大写字母。
#!/bin/bash
echo $BASH_VERSION
Bash 内置了许多变量:
$$ - 当前 shell 的进程 ID (PID)
$! - 上一个后台命令的进程 ID (PID)
$? - 上一个命令的退出状态
$0 - 当前命令的名称
$1 - 当前命令的第一个参数的名称
$9 - 当前命令的第九个参数的名称
$@ - 当前命令的所有参数(保留空格和引号)
$* - 当前命令的所有参数(不保留空格和引号)
格式化变量
# The string 'Not defined' is printed if the variable "message" has not been defined.
echo ${message:-"Not defined"}
# The string "Not defined but now defined and assigned", if the variable did not exist prior.
echo ${message:="Not defined but now defined and assigned"}
# The string "Error: the variable does not exist" is printed if you try to print a variable does not exist.
echo ${message:?"Error: the variable does not exist"}
var1='shell scripting'
var2='BASH SCRIPTING'
echo ${var1^^} # Print a variable in all uppercase.
echo ${var1^} # Convert the first letter to uppercase.
echo ${var2,,} # Print a variable in all lowercase.
echo ${var2,} # Convert the first letter to lowercase.
循环
C 风格的循环
#!/bin/bash
for ((i=0; i<10; i++))
do
echo $i
done
Python风格的for循环
#!/bin/bash
for number in "1 2 3 4 5"
do
echo $number
done
while 循环
#!/bin/bash
count=0
while [[ $count -lt 10 ]]
do
echo $count
(( count++ ))
done
直到循环
#!/bin/bash
count=10
until [[ $count -eq 0 ]]
do
echo $count
(( count-- ))
done
选择循环
您可以使用选择循环为 shell 脚本创建菜单类型的界面。
#!/bin/bash
options="Yes No Maybe"
ps3="Select your option" # Customize your menu selection.
select option in $options
do
if [[ $option == "Yes" ]]
then
echo "You chose Yes"
elif [[ $option == "No" ]]
then
echo "You chose No"
exit
elif [[ $option == "Maybe" ]]
then
echo "You chose Maybe"
else
echo "Invalid option chosen"
exit
fi
done
Bash条件语句支持其他编程语言中
常见的if、elif 和 else条件运算符。
Bash 支持的比较运算符有:
- 整数比较运算符
- 字符串比较运算符
- 复合比较运算符
- 文件比较运算符
整数比较运算符
-eq 等于
-ne 不等于
-gt 大于
-ge 大于或等于
-lt 小于
-le 小于或等于
< 表示小于——请用双括号括起来
<= 表示小于或等于
> 大于
>= 表示大于或等于
字符串比较运算符
= 等于
== 等于
= 不等于
< 小于 ASCII 字母顺序
> 大于 ASCII 字母顺序
-z 字符串为空(即长度为零)
-n 字符串不为空(即长度不为零)
复合比较运算符
-a 逻辑和
-o 逻辑或
#!/bin/bash
a=1
b=2
if [[ $a -gt $b ]]
then
echo $a is greater than $b
elif [[ $a -lt $b ]]
then
echo $a is less than $b
elif [[ $a -eq $b ]]
then
echo $a is equal to $b
else
echo "unknown condition"
fi
[[ -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
-r file has read permission
-w file has write permission
-x file has execute permission
file1 -nt file2 file file1 is newer than file2
file1 -ot file2 file file1 is older than file2
file1 -ef file2 files file1 and file2 are hard links to the same file
[[ ... ]] && [[ ... ]] # And
[[ ... ]] || [[ ... ]] # Or
Case
语句可以简化和替换一系列 if elif else 语句,它还可以与 Select 语句一起使用。
#!/bin/bash
read -p "Make your choice: " option
case $option in
"Yes")
echo "You chose 'Yes'";;
"Maybe")
echo "You chose 'Maye'";;
"No")
echo "You chose 'No'";;
*) # default option
echo "Unknown option";;
esac
# Create a Menu system with Select and Case
options="Yes No Maybe"
select option in $options
do
case $option in
"Yes")
echo "You chose 'Yes'";;
"Maybe")
echo "You chose 'Maye'";;
"No")
echo "You chose 'No'"
exit;;
*) # default option
echo "Unknown option";;
esac
done
Bash 中的函数
与常规编程语言中的函数类似,唯一的区别在于调用方式:执行函数时,只需输入函数名,无需括号。此外,Bash 函数没有返回值。
#!/bin/bash
# Define a simple function
function greeter() {
echo "Hello, world!"
}
# Define a function that accepts arguments
function greeter1() {
echo $1
}
运行以下命令调用该函数greeter以显示:
Hello, World!"
然后通过传递参数greeter Hello, world来调用显示函数:
Hello, World!"
用户输入
您可以使用 Bash 的read关键字来接收用户输入。
#!/bin/bash
read var # The user inputted value is saved in a variable called *var*
read -p "Enter your name" name # A prompt "Enter your name" is displayed to the user and the supplied value is saved in the variable "name".
read -s -p "Enter your password" password # "This hides the user inputted value. Useful for password inputs.
read -p "Enter all your names" -a names # If you want to accept more than one value from users. It creates an Array object called *names*
算术
#!/bin/bash
a=1
b=2
$((a + b)) # Addition
$((a - b)) # Subtraction
$((a * b)) # Multiplication
$((a / b)) # Division
$((a % b)) # Modulus
如果你想进行高级算术运算,例如处理浮点数、求数字的平方根等等,你应该使用内置的bc命令。
#!/bin/bash
echo "scale=2; sqrt((49)) | bc -l # scale determines the number of decimal places.
echo "scale=3; 3.142 * 4.2" | bc -l
Bash 中的数组
有两种类型的变量
- 标量变量(包含单个值)
- 数组变量(包含多个值)Bash 数组是从零开始的数组,即从位置零开始。
#!/bin/bash
names=(Jack John Jill Scot)
${names[@]} # This prints all the variables
${#names[@]} # Counts the number of items in the *names* array.
${!names[@]} # Returns the indexes of the items in the array.
unset names[<index>] # Removes the item in the array at the specified index.
${names[0]} # Returns the first item of the array.
${names[-1]} # Returns the last item of the array.
技巧、窍门和工具
- 使用 shellcheck.net 查找 shell 脚本中的错误。
- 你可以像这样运行 shell 脚本来调试它
bash -x script.sh。这将以调试模式运行脚本。 - 你可以在 shell 脚本中设置断点。
#!/bin/bash
set -x
message="This is a shell scripting tutorial"
echo $message
set +x
至此,我们五分钟的 Bash shell 脚本入门教程就结束了。希望它能开启你精通 Bash shell 脚本的旅程。
文章来源:https://dev.to/pystar/learn-shell-scripting-in-5-minutes-5fk4