Arr*_*cal 5 command-line bash scripts
我有以下函数来计算我的 bash 脚本中目录中的文件数。
file_count() {
no_of_files=$(find "$1" -maxdepth 1 -type f -printf '.' | wc -c)
}
Run Code Online (Sandbox Code Playgroud)
我想在不同的目录上重复使用它,并将计数保存到每个目录的变量中。目前要做到这一点,我使用
file_count $somedir
files_in_somedir="$no_of_files"
Run Code Online (Sandbox Code Playgroud)
我知道我no_of_files每次都在函数外部设置变量,并希望将其设置为函数的本地变量,而不是在主脚本中设置中间变量。这是以防万一有一些错误意味着变量在函数调用之间不会改变(可能错误输入函数名称),并且使用了旧值no_of _files。
如果我的功能是:
file_count() {
local no_of_files=$(find "$1" -maxdepth 1 -type f -printf '.' | wc -c)
}
Run Code Online (Sandbox Code Playgroud)
我如何轻松设置这些目录计数变量?
Bash 函数不像其他编程语言中的函数,它们更像是命令。这意味着它们没有经典的返回值,但是
退出/返回代码。这是一个 0-255 范围内的整数,其中 0 表示“成功”,每隔一个值表示一个错误。如果您尝试指定一个超出此范围的数字,它将取模 256(从您的数字中添加或减去 255,直到它适合范围 0-255)。
此代码会自动设置为在函数内部执行的最后一条语句的返回码,除非您使用return命令手动设置它,如下所示:
return 1
Run Code Online (Sandbox Code Playgroud)输出流。每个 Bash 函数都可以将任意字符串写入输出流(STDOUT 和 STDERR),就像普通脚本一样。输出可以直接来自您在函数中运行的命令,也可以使用echo.
但是,不是让这个输出显示在控制台中,您可以在运行函数时捕获它,例如使用 Bash 的命令替换语法,并将其存储在主脚本中的变量中:
example_function() {
# do something useful
echo "return this message"
}
returned_value="$(example_function)"
Run Code Online (Sandbox Code Playgroud)所以你的代码必须是这样的:
file_count() {
find "$1" -maxdepth 1 -type f -printf '.' | wc -c
# the line above already prints the desired value, so we don't need an echo
}
files_in_somedir="$(file_count "$somedir")"
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅bash 脚本中的返回值(在 Stack Overflow 上)。