bash 如何在bash中获得第n个位置参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1497811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:34:02  来源:igfitidea点击:

How to get the nth positional argument in bash?

bashargumentscommand-line-arguments

提问by hcs42

How to get the nth positional argument in Bash, where nis variable?

如何n在 Bash 中获取第th 个位置参数,变量在哪里n

回答by Paused until further notice.

Use Bash's indirection feature:

使用 Bash 的间接功能:

#!/bin/bash
n=3
echo ${!n}

Running that file:

运行该文件:

$ ./ind apple banana cantaloupe dates

Produces:

产生:

cantaloupe

Edit:

编辑:

You can also do array slicing:

您还可以进行数组切片:

echo ${@:$n:1}

but not array subscripts:

但不是数组下标:

echo ${@[n]}  #  WON'T WORK

回答by Johannes Weiss

If Nis saved in a variable, use

如果N保存在变量中,请使用

eval echo ${$N}

if it's a constant use

如果是经常使用

echo 

since

自从

echo 

does not mean the same!

不一样!

回答by rahul

Read

Handling positional parameters

处理位置参数

and

Parameter expansion

参数扩展

$0: the first positional parameter

$0:第一个位置参数

$1 ... $9: the argument list elements from 1 to 9

$1 ... $9:从1到9的参数列表元素

回答by Zen

As you can see in the Bash by Example, you just need to use the automatic variables $1, $2, and so on.

正如您在Bash by Example 中看到的,您只需要使用自动变量 $1、$2 等。

$# is used to get the number of arguments.

$# 用于获取参数的数量。