参数、返回值与作用域

Bash 脚本入门

Alex Scriven

Data Scientist

向 Bash 函数传参

向函数传参与向脚本传参类似,使用 $1 记法。

还可使用之前介绍的 ARGV 特性:

  • 各参数分别用 $1$2 访问。
  • $@$* 返回 ARGV 中的全部参数
  • $# 返回参数个数
Bash 脚本入门

传参与示例

让我们把文件名作为参数传入函数演示。我们将遍历并打印它们。

function print_filename {
    echo "The first file was $1"

for file in $@ do echo "This file has name $file" done }
print_filename "LOTR.txt" "mod.txt" "A.py"

 

 

 

The first file was LOTR.txt
This file has name LOTR.txt
This file has name mod.txt
This file has name A.py
Bash 脚本入门

编程中的作用域

 

"作用域"指变量的可见性。

  • "全局"表示在程序任意位置可访问,包括 FOR、IF、函数等。
  • "局部"表示仅在程序的某一部分可访问。

为什么重要?若访问仅具局部作用域的内容,程序可能报错!

Bash 脚本入门

Bash 函数中的作用域

与多数语言(如 Python、R)不同,Bash 变量默认都是全局的。

function print_filename {
    first_filename=$1
}

print_filename "LOTR.txt" "model.txt" echo $first_filename
LOTR.txt

注意:全局作用域更易引发意外,请谨慎。

Bash 脚本入门

在 Bash 函数中限制作用域

可用 local 关键字限制变量作用域。

function print_filename {
    local first_filename=$1
}

print_filename "LOTR.txt" "model.txt" echo $first_filename


 

问:为什么没有报错,只是空行?

答:first_filename 被赋值为全局的第一个 ARGV 元素($1)。

我在无参数下运行脚本(bash script.sh),因此该元素为空。请注意!

Bash 脚本入门

返回值

我们会传入参数——那如何取回结果?

Bash 的 return 仅用于表示成功(0)或失败(1-255),结果存于全局变量 $?

可选做法:

  1. 赋值给全局变量
  2. 在函数最后一行用 echo 输出,并用子 shell 捕获
Bash 脚本入门

一次返回错误

来看一次返回错误:

function function_2 {
    echlo # 'echo' 的拼写错误
}

function_2 # 调用函数 echo $? # 打印返回值
script.sh: line 2: echlo: command not found
127

发生了什么?

  1. 调用函数时报错
    • 脚本尝试将"echlo"当作程序,但不存在
  2. $? 的返回值为 127(错误)
Bash 脚本入门

正确返回

echo 与子 shell 捕获正确返回值:

function convert_temp {
    echo $(echo "scale=2; ($1 - 32) * 5 / 9" | bc)
}

converted=$(convert_temp 30) echo "30F in Celsius is $converted C"
30F in Celsius is -1.11 C
  • 注意我们不再创建中间变量。
Bash 脚本入门

Passons à la pratique !

Bash 脚本入门

Preparing Video For Download...