Linux command
function 命令
文本
涉及管道、覆盖或删除,执行前请先确认路径和参数。
常用示例
Define a function
function greet() { echo "Hello $1"; }
Call the function
greet [World]
List defined functions
declare -F
Show function definition
declare -f [function_name]
Unset function
unset -f [function_name]
说明
function is a shell keyword for defining reusable command groups. Functions encapsulate commands, accept parameters, and can return exit status values. Functions enable code reuse, modularity, and cleaner scripts. They have local scope for variables with the `local` keyword. Parameters are accessed through positional variables ($1, $2, etc.). In bash, both `function name() { ...; }` and `name() { ...; }` syntax define functions. The POSIX-portable form omits the `function` keyword. In ksh and zsh, the `function` keyword is also supported.
参数
- $1, $2, etc.
- Positional parameters.
- $@
- All parameters.
- return _N_
- Exit function with status.
- local _VAR_
- Declare local variable.
FAQ
What is the function command used for?
function is a shell keyword for defining reusable command groups. Functions encapsulate commands, accept parameters, and can return exit status values. Functions enable code reuse, modularity, and cleaner scripts. They have local scope for variables with the `local` keyword. Parameters are accessed through positional variables ($1, $2, etc.). In bash, both `function name() { ...; }` and `name() { ...; }` syntax define functions. The POSIX-portable form omits the `function` keyword. In ksh and zsh, the `function` keyword is also supported.
How do I run a basic function example?
Run `function greet() { echo "Hello $1"; }` in a terminal, then adjust file names, paths, flags, or remote targets for your system.
What does $1, $2, etc. do in function?
Positional parameters.