I'm hoping to get some insight on assigning a variable when calling a function. The code below looks at my array and checks if the path exists. My actual code will have multiple arrays and I would like to define a specific array when I call the function, but I am getting a bad substitution error.
This is the code without assigning variables in function
## MY ARRAY
array=(
/Library/Application\ Support/
/Library/LaunchAgents/folder_that_doesnt_exist
)
## MY FUNCTION
results ()
{
for i in "${!array[@]}"; do
if [[ -e "${array[$i]}" ]]; then
echo "**Found**: "${array[$i]}""
else echo "Not Found: "${array[$i]}""
fi
done
}
results
##Output:
**Found**: /Library/Application Support/
Not Found: /Library/LaunchAgents/folder_that_doesnt_exist
Example attempt of assigning the variables, which failed:
array=(
/Library/Application\ Support/
/Library/LaunchAgents/folder_that_doesnt_exist
)
results ()
{
for i in $1; do
if [[ -e $2 ]]; then
echo "**Found**: $2"
else echo "Not Found: $2"
fi
done
}
results "${!array[@]}" "${array[$i]}"
array=(
/Library/Application\ Support/
/Library/LaunchAgents/folder_that_doesnt_exist
)
results ()
{
for i in "${@}" ; do
if [[ -e "$i" ]]; then
echo "**Found**: $i"
else echo "Not Found: $i"
fi
done
}
results "${!array[@]}" "${array[$i]}"
I'm not sure where "@{!array[@]} is coming from, I used "${array[@]}" in my original example. Do you know how I can pass "${array[@]}" into the function? I tried SEA's example but it outputs:
Not Found: 0
Not Found: 1
**Found**: /Library/Application Support/
To clarify, I have several arrays that I would like to call independently. What I'm trying to achieve is- pass an array into that function by just typing:
results "${!array1[@]}"
results "${!array2[@]}"
and have it output:
**Found**: /path/defined/in/array1
Not Found: /path/that does/not/exist/defined/in/array1
**Found**: /path/defined/in/array2
Not Found: /path/that does/not/exist/defined/in/array2
But I am having trouble defining the array to the function, if I type in "${array[@]}" & "${array[$i]}" manually into the for loop, it works fine. But because I will have 10-20 arrays, I want to call them independently without typing and maintaining all that embedded code.
This is not obvious when you post an example containing one and exactly one array used directly.
What do you mean by 'call independently'? Are you trying to make an array-full-of-arrays kind of thing or what?
"${array[$i]}" is wrong, for does not work that way, see my above post.
By doing function "${array[@]}" It all ends up in $@ inside the function. To show further:
dosomething () {
for i in "$@"
do
echo "dosomething: $i"
done
}
array1=( "a b" c "d e" )
array2=( q w e r t )
dosomething "${array1[@]}" extra stuff "${array2[@]}"
This is not pseudo-code. Paste it and it should work.
Yes, I was not clear in my initial post in an attempt to keep things concise, but thank you for your last post it exemplified exactly what I was looking for