n.r*_*.r. 32 bash array parameter
如何$@
在不首先将所有位置参数复制到这样的另一个数组的情况下在 Bash 中获取切片?
argv=( "$@" )
echo "${argv[@]:2}";
Run Code Online (Sandbox Code Playgroud)
ter*_*don 48
您可以使用与任何其他数组相同的格式。要从 中提取第二个和第三个元素$@
,您可以执行以下操作:
echo "${@:1:2}"
- -
| |----> slice length
|------> slice starting index
Run Code Online (Sandbox Code Playgroud)
Gab*_*les 10
代替some_array_variable
在代码中使用(argv
在您的情况下),只需@
在该变量名称的位置使用即可。该符号@
代表输入参数 array,您可以像对待任何其他数组一样对待它。令人困惑的是,我们习惯于看到它几乎总是与$
这样的字符配对:$@
,因此我们没有意识到该@
字符就是数组本身,也可以单独用作数组变量。
所以,这里有一些例子:
\n从输入参数数组 中切片,@
通常可以简单地看到和访问该数组$@
:
# array slicing basic format 1: grab a certain length starting at a certain\n# index\necho "${@:2:5}"\n# \xe2\x94\x82 \xe2\x94\x82\n# \xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80> slice length\n# \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80> slice starting index \n\n# array slicing basic format 2: grab all remaining array elements starting at a\n# certain index through to the end\necho "${@:2}"\n# \xe2\x94\x82\n# \xe2\x94\x82\n# \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80> slice starting index \n
Run Code Online (Sandbox Code Playgroud)\n以下是对我自己的一般性提醒,可能对登陆此页面的其他人也有好处。
\n# store a slice from an array into a new array\nnew_array=("${@:4}")\n\n# print the entire array\necho "new_array = ${new_array[@]}"\n
Run Code Online (Sandbox Code Playgroud)\n这是 bash 中通用数组切片和数组元素访问的可运行示例,受到此源的启发:
\n(@
如果需要,可以用作输入参数数组,而不是a
下面的,根据您的用例)
a=(one two three four five six) # define a new array, `a`, with 6 elements\necho "$a" # print first element of array a\necho "${a}" # print first element of array a\necho "${a[0]}" # print first element of array a\necho "${a[1]}" # print *second* element of array a\necho "${#a[@]}" # print number of elements in array a\necho "${a[@]:1:3}" # print 2nd through 4th elements; ie: the 3 elements\n # starting at index 1, inclusive, so: indices 1, 2, and 3\n # (output: `two three four`)\necho "${a[@]:1}" # print 2nd element onward\n
Run Code Online (Sandbox Code Playgroud)\n将上面的所有代码块复制并粘贴到名为 的文件中array_slicing_demo.sh
,并将其标记为可执行,chmod +x array_slicing_demo.sh
以便您可以运行它。或者,只需从此处的eRCaGuy_hello_worl d 存储库下载我的演示array_slicing_demo.sh文件。
然后,像这样运行它:
\n./array_slicing_demo.sh a b c d e f g h i j k\n
Run Code Online (Sandbox Code Playgroud)\n...您将看到以下输出:
\n\n\nRun Code Online (Sandbox Code Playgroud)\nb c d e f\nb c d e f g h i j k\nnew_array = d e f g h i j k\none\none\none\ntwo\n6\ntwo three four\ntwo three four five six\n
关键词:bash中的数组访问;bash 数组索引;在 bash 中访问数组中的元素;bash 数组切片;在 bash 中打印数组;在 bash 中打印数组元素
\n 归档时间: |
|
查看次数: |
18229 次 |
最近记录: |