Bash 脚本入门
Alex Scriven
Data Scientist
向函数传参与向脚本传参类似,使用 $1 记法。
还可使用之前介绍的 ARGV 特性:
$1、$2 访问。$@ 与 $* 返回 ARGV 中的全部参数$# 返回参数个数让我们把文件名作为参数传入函数演示。我们将遍历并打印它们。
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
"作用域"指变量的可见性。
为什么重要?若访问仅具局部作用域的内容,程序可能报错!
与多数语言(如 Python、R)不同,Bash 变量默认都是全局的。
function print_filename { first_filename=$1 }print_filename "LOTR.txt" "model.txt" echo $first_filename
LOTR.txt
注意:全局作用域更易引发意外,请谨慎。
可用 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 的 return 仅用于表示成功(0)或失败(1-255),结果存于全局变量 $?。
可选做法:
echo 输出,并用子 shell 捕获来看一次返回错误:
function function_2 { echlo # 'echo' 的拼写错误 }function_2 # 调用函数 echo $? # 打印返回值
script.sh: line 2: echlo: command not found
127
发生了什么?
$? 的返回值为 127(错误)用 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 脚本入门