6

I wanted to know the "right" way to do this. Basically, I have a list of files that are in an array called current. This is declared as a global variable that looks like this: current=(). I have successfully put all the files in this array. But now, I am going through and parsing arguments to filter out these files and directories.

For example, to implement the -name '*.pattern' command, I pass in the pattern to process_name() which does this:

process_name ()
{
    local new_cur=()
    for i in "${current[@]}"; do
        if [[ "$i" == "$1" ]]; then
            new_cur+=("$i")
        fi
    done
    current=( "${new_cur[@]}" )
}

After the loop finishes I want to "clear" my current array. Then I want to loop over the new_cur array, and basically make it equal to current, or if I can, just do something like $current = $new_cur (although I know this won't work).

I've tried doing this after the for loop (in process_name()), but my array current doesn't actually change:

current=( "${new_cur[@]}" )

Is there a good way to do this? Or a right way to do this?

2 Answers 2

18

To reset an array just use:

current=()

This will delete old entries and declare a 0 element array.

Sign up to request clarification or add additional context in comments.

2 Comments

How would I load the values from new_cur into current after resetting them?
You already had for loop to load values from array1 to array2.
3

You can simply clone an array using array1=( "${array2[@]}" ). For example:

[STEP 100] $ echo $BASH_VERSION
4.3.33(1)-release
[STEP 101] $ cat foo.sh
current=(aa bb cc)

process_name ()
{
    local new_cur=()

    for i in "${current[@]}"; do
        if [[ "$i" == "$1" ]]; then
            new_cur+=("$i")
        fi
    done
    current=( "${new_cur[@]}" )
}

process_name aa

for i in "${current[@]}"; do
    printf '%s\n' "$i"
done
[STEP 102] $ bash foo.sh
aa
[STEP 103] $

12 Comments

Will this overwrite all the values at current?
Yes, the old array will be overwritten.
I did some testing and even though my local variable has the correct values... after resetting the array with the solution you provided, current ends up empty, basically, cur_new never gets written into it. I'm doing current=( "${cur_new[@]}" )
It does not work for you? Can you post your new code?
Just updated it.. I realized I didn't need to check for the types yet. And printing out new_cur in the loop yields correct results. However, once out of the function, printing out current doing for i in "${current[@]}"; do .. printf '%s\n' "$i" .. done does not work :(
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.