如何将数组参数传递给Bash脚本

编程入门 行业动态 更新时间:2024-10-26 11:16:42
本文介绍了如何将数组参数传递给Bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让我惊讶的是,在搜索1小时后我没有找到答案. 我想像这样将数组传递给我的脚本:

It is surprising me that I do not find the answer after 1 hour search for this. I would like to pass an array to my script like this:

test.sh argument1 array argument2

我不想将其放在另一个bash脚本中,如下所示:

I DO NOT want to put this in another bash script like following:

array=(a b c) for i in "${array[@]}" do test.sh argument1 $i argument2 done

推荐答案

Bash数组不是一流的值"-您不能像一个事物"那样传递它们.

Bash arrays are not "first class values" -- you can't pass them around like one "thing".

假设test.sh是一个bash脚本,我会做

Assuming test.sh is a bash script, I would do

#!/bin/bash arg1=$1; shift array=( "$@" ) last_idx=$(( ${#array[@]} - 1 )) arg2=${array[$last_idx]} unset array[$last_idx] echo "arg1=$arg1" echo "arg2=$arg2" echo "array contains:" printf "%s\n" "${array[@]}"

并像调用它一样

test.sh argument1 "${array[@]}" argument2

更多推荐

如何将数组参数传递给Bash脚本

本文发布于:2023-06-04 19:07:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/503319.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   如何将   脚本   参数   Bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!