如何将传递给我的bash脚本的所有参数传递给我的函数? [重复]

本文探讨如何在Bash脚本中将接收到的可变数量参数传递给自定义函数,重点在于避免硬编码参数,并分享了通过数组访问脚本参数的技巧和示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:How to pass all arguments passed to my bash script to a function of mine? [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 13 days ago . 13天前关闭。

Let's say I have defined a function abc() that will handle the logic related to analyzing the arguments passed to my script. 假设我已经定义了一个function abc() ,它将处理与分析传递给脚本的参数有关的逻辑。

How can I pass all arguments my bash script has received to it? 如何将bash脚本收到的所有参数传递给它? The number of params is variable, so I can't just hardcode the arguments passed like this: 参数的数量是可变的,所以我不能仅仅对这样传递的参数进行硬编码:

abc $1 $2 $3 $4

Edit . 编辑 Better yet, is there any way for my function to have access to the script arguments' variables? 更好的是,我的函数是否可以访问脚本参数的变量?


#1楼

参考:https://stackoom.com/question/FzVJ/如何将传递给我的bash脚本的所有参数传递给我的函数-重复


#2楼

I needed a variation on this, which I expect will be useful to others: 我需要对此进行更改,我希望这对其他人会有用:

function diffs() {
        diff "${@:3}" <(sort "$1") <(sort "$2")
}

The "${@:3}" part means all the members of the array starting at 3. So this function implements a sorted diff by passing the first two arguments to diff through sort and then passing all other arguments to diff, so you can call it similarly to diff: "${@:3}"部分表示从3开始的数组的所有成员。因此,此函数通过将前两个参数传递给diff并随后将所有其他参数传递给diff来实现排序的diff,因此您可以类似于diff来称呼它:

diffs file1 file2 [other diff args, e.g. -y]

#3楼

It's worth mentioning that you can specify argument ranges with this syntax. 值得一提的是,您可以使用此语法指定参数范围。

function example() {
    echo "line1 ${@:1:1}"; #First argument
    echo "line2 ${@:2:1}"; #Second argument
    echo "line3 ${@:3}"; #Third argument onwards
}

I hadn't seen it mentioned. 我没有看到它提到。


#4楼

abc "$@"

$@表示提供给bash脚本的所有参数。


#5楼

使用$@变量,该变量将扩展为所有用空格分隔的命令行参数。

abc "$@"

#6楼

Here's a simple script: 这是一个简单的脚本:

#!/bin/bash

args=("$@")

echo Number of arguments: $#
echo 1st argument: ${args[0]}
echo 2nd argument: ${args[1]}

$# is the number of arguments received by the script. $#是脚本接收的参数数量。 I find easier to access them using an array: the args=("$@") line puts all the arguments in the args array. 我发现使用数组更容易访问它们: args=("$@")行将所有参数放入args数组中。 To access them use ${args[index]} . 要访问它们,请使用${args[index]}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值