1

I would like to move files I have from one directory to another using an array of keywords to find and categorize the files. I have some syntax issue with my find command and I'm not sure how to solve it. The error is:

./Process.sh: line 7: \*building\*: syntax error: 
        operand expected (error token is "\*building\*")

Here is the script:

#!/bin/bash
declare -a keyword=("*building*")
declare -a directory=("Building")

for i in "${keyword[@]}"
do
    echo find /run/media/_Incoming/ -type f -name "${keyword[$i]}" \
        -exec echo mv -t /run/media/"${directory[$i]}"/ {} +
done

1 Answer 1

2

Arrays use numbers such as 0, 1, 2 as indices. Your index $i is not a number, but an element of the array keyword. ${keyword[$i]} expands to ${keyword[*building*]} which is not a valid array entry.

You probably wanted to write:

#!/bin/bash
declare -a keyword=("*building*")
declare -a directory=("Building")

for i in "${!keyword[@]}"
do
    echo find /run/media/_Incoming/ -type f -name "${keyword[$i]}" \
        -exec echo mv -t /run/media/"${directory[$i]}"/ {} +
done

${!keyword[@]} (mind the ! at the beginning) expands to all indices of array keyword. Because of the echo in front of find this will print the command

find /run/media/_Incoming/ -type f -name *building* -exec echo mv -t /run/media/Building/ {} +
Sign up to request clarification or add additional context in comments.

1 Comment

Could be a good idea to suggest associative arrays: declare -A ass=([Building]="*building*"); for i in "${!ass[@]}"; do ...

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.