简体   繁体   English

for循环中的bash脚本数组变量

[英]bash script array variables in for loop

I am trying to write bash script that get 3 arguments of paths.我正在尝试编写获取 3 个路径参数的 bash 脚本。 for ex /tmp/1 /tmp/2 /tmpnew I want to iterate over the argument except the last one and each time copy the file to the path of the last argument.对于 ex /tmp/1 /tmp/2 /tmpnew 我想迭代除最后一个参数之外的参数,并且每次将文件复制到最后一个参数的路径。

I have problem with echo '${files[$(($len))]}' inside the for.我在 for 中遇到 echo '${files[$(($len))]}' 问题。 I cant pull the last argument like that.我不能这样拉最后一个论点。

files=( "$@" )

len=${#files[@]}
echo $len
for (( i=0; i<$(( $len -1 )); i++ ))
    do
        echo ${files[$(($len))]}
        echo ${files[$i]}
    done

The last element is ${files[len-1]} , or simply ${files[-1]} .最后一个元素是${files[len-1]} ,或者只是${files[-1]}

Similarly, you can use just ${files[i]} .同样,您可以只使用${files[i]} If the array is not associative, bash interprets the index as an arithmetic expression.如果数组不是关联的,bash 会将索引解释为算术表达式。

#!/bin/bash
files=("$@")

len=${#files[@]}
echo $len
for (( i=0; i<len-1; i++ )) ; do
    echo "${files[-1]}"
    echo "${files[i]}"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM