Functions, used in script(Linux)

本文介绍了Bash脚本中函数的基本用法,包括两种定义方式、参数传递、返回值设置、变量作用域及如何重写已有命令等内容。

Function 可以有两种写法:

function_name () {
<commands>
}

or

function function_name {
<commands>
}

在bash中,function的参数传递与c语言等不一样,在调用时是直接在函数名后面写上要传递的参数,function_name argument  argument

[@entmcnode15] try $ cat arguments.sh 
#!/bin/bash
# Passing arguments to a function
print_something () {
echo Hello $1
echo second is $2
}
print_something Mars Lukas
print_something Jupiter Lando
[@entmcnode15] try $ ./arguments.sh 
Hello Mars
second is Lukas
Hello Jupiter
second is Lando
[@entmcnode15] try $ 
解释:
print_something Mars Lukas
直接调用函数名,后面跟的两个参数分别作为$1与$2传入函数。


Return Values

在bash函数中, use the keyword return to indicate a return status.

[@entmcnode15] try $ ./arguments.sh 
Hello Mars
second is Lukas
Hello Jupiter
second is Lando
The previous function has a return value of 5
[@entmcnode15] try $ cat arguments.sh 
#!/bin/bash
# Passing arguments to a function
print_something () {
echo Hello $1
echo second is $2
return 5
}
print_something Mars Lukas
print_something Jupiter Lando
echo The previous function has a return value of $?
[@entmcnode15] try $ 
<span style="background-color: rgb(255, 255, 255);">$?为上一轮命令执行的return status,return value是5</span>

Variable Scope

默认情况下variable is global,在其所在的script中可见;若在函数中将变量定义为local,则只在此函数中可见,用关键字local,local var_name=<var_value>

<pre name="code" class="cpp">[@entmcnode15] try $ ./function.sh 
Before function call: var1 is global 1 : var2 is global 2
Inside function: var1 is local 1 : var2 is global 2
Inside function,modify value: var1 is changed again : var2 is 2 changed again
After function call: var1 is global 1 : var2 is 2 changed again
[@entmcnode15] try $ cat function.sh
#!/bin/bash
# Experimenting with variable scope
var1='global 1'
var2='global 2'
echo Before function call: var1 is $var1 : var2 is $var2
var_change () {
local var1='local 1'
echo Inside function: var1 is $var1 : var2 is $var2
var1='changed again'
var2='2 changed again'
echo Inside function,modify value: var1 is $var1 : var2 is $var2
}
var_change
echo After function call: var1 is $var1 : var2 is $var2


Overriding Commands

我们可以将我们的函数命名成与已有的命令同名,这样就可以对命令进行重写。但注意在函数中调用同名命令时需要加上command ,否则就会进入死循环。

[@entmcnode15] try $ cat overwrite.sh 
#!/bin/bash
echo(){
    command echo override echo
}
echo
[@entmcnode15] try $ ./overwrite.sh 
override echo
注意:
command echo override echo
前要加command,否则echo函数一直调用自身,进入死循环。

Summary

function <name> or <name> ()
Create a function called name.
return <value>
Exit the function with a return status of value.
local <name>=<value>
Create a local variable within a function.
command <command>
Run the command with that name as opposed to the function with the same name.
### Linux Shell Script Example and Explanation A `shell` script in Linux is essentially a text file containing one or more commands that are executed sequentially by the shell interpreter (e.g., Bash). Below is an example of a simple `linux.sh` script with explanations. #### Example: A Basic Shell Script (`linux.sh`) This script demonstrates how to display system information such as hostname, current date, disk usage, memory usage, etc. ```bash #!/bin/bash # Display Hostname echo "Hostname: $(hostname)" # Display Current Date and Time echo "Current Date & Time: $(date)" # Check Disk Usage echo "Disk Usage:" df -h | grep '^/' # List only mounted partitions # Memory Information echo "Memory Usage:" free -m # Show memory details in MB units # Process Listing echo "Top 5 CPU Consuming Processes:" ps aux --sort=-%cpu | head -n 6 # Top processes sorted by CPU consumption ``` The above script includes several common tasks performed using built-in Unix/Linux utilities like `hostname`, `date`, `df`, `free`, and `ps`. Each line performs specific actions: - The first line specifies the interpreter used for executing this script (`/bin/bash`) [^1]. - Commands prefixed with `$()` execute subcommands within parentheses. - Comments start with `#`. When running scripts, ensure they have executable permissions set via `chmod`. For instance: ```bash chmod +x linux.sh ./linux.sh ``` Additionally, when working inside emulated environments created through tools like QEMU, certain configurations may be required depending upon kernel parameters passed during invocation [^1]. For example, specifying `-kernel`, `-initrd`, along with appropriate append strings ensures proper bootstrapping into minimalistic root filesystems based around BusyBox implementations. Regarding environment variables which might influence behavior either directly referenced from within your custom `.sh` files or indirectly affecting binaries called therein; refer summarized guidelines provided elsewhere regarding their management under typical GNU/Linux distributions [^2]. Lastly, while handling large datasets generated possibly due execution logs produced after invoking complex pipelines involving multiple chained operations consider precautions against exceeding permissible limits imposed internally at various stages including but not limited to filename suffix exhaustion scenarios encountered previously discussed contextually relevant situations concerning data splitting mechanisms implemented utilizing standard utility functions available across POSIX compliant systems [^4]. ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值