简体   繁体   中英

bash script array variables in for loop

I am trying to write bash script that get 3 arguments of paths. 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.

I have problem with echo '${files[$(($len))]}' inside the for. 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]} .

Similarly, you can use just ${files[i]} . If the array is not associative, bash interprets the index as an arithmetic expression.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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