Arrays with UNIX Commands

Hi,

Can anyone please guide me to pass the values for an array during runtime and use it.

I am using Linux OS.

what I am trying to do is, i am trying to pass the output of the ls <source folder> command to a array and copy the list of files in the array to a different (Destination) folder.

How to do the same.

#!/bin/sh
i=$(ls /home/e1013699/NewFiles/20150721/extracts | wc -l)
a=$(ls NewFiles/20150721/extracts)
echo ${a[@]}

Correct me if i am wrong

Thanks in Advance.

It is a common mistake of beginning shell programmers to abuse arrays as the solution to all problems. "Enumerate the universe, shoehorn into shell variable, force-feed into command" is a poor habit, sub-optimal, prone to many pitfalls and corner cases, and generally unnecessary.

Do you actually need an array here? Why not cp -r ?

Two comments:
The shebang indicates you're using sh which doesn't offer arrays. Use e.g. bash or ksh .
There's no array definition command, just a variable assignment. In bash , try a=($(ls)) .

Thanks for the reply.

@Corona688

Yes i need a array as i have to find what files are there in that location and backup them from a location, if exists and replace the same.

You don't need an array for your purpose; feed ls 's output into e.g. a while loop to achieve the desired result.

Just try doing ... Hope this will solve your purpose

for i in `ls NewFiles/20150721/extracts`; do echo $i; done; 

See useless use of backticks.

2 Likes

Thanks, i was able to get what i wanted.