LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Bash script problem (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-problem-922346/)

harishisnow 01-06-2012 01:22 AM

Bash script problem
 
Hello,

I am writing a bash script which uses the find command and stores the result of the find command to a variable. How do I retreive the values present in the variable one by one?

ie:
#!/bin/sh

VAR=`find /home/par_dir -type f -name "target_file" -print`

(The result of the find command is:
/home/par_dir/abc/target_file
/home/par_dir/xyz/target_file
)

Now, when I use
for linee in VAR
do
echo $linee
done

I am not able to retreive the rows one by one.
Can anybody help me in doing so?

Thanks in advance..!!

Regards,
Harish

corp769 01-06-2012 01:31 AM

Best way to go, IMO, is using an array for this. Have a look here - http://stackoverflow.com/questions/1...o-a-bash-array

Cheers,

Josh

David the H. 01-06-2012 02:06 AM

You'll find just about everything you need to know here:

http://mywiki.wooledge.org/BashFAQ/001


I recommend using a loop to set the files into an array instead of a scalar variable.

Code:

while IFS="" read -r -d "" file; do array+=( "$file" ) ; done < <( find . -print0 )

corp769 01-06-2012 02:13 AM

Technically, either way would work. Besides, that's what I meant by giving that link to the OP. Maybe you were looking at something different on that page?

David the H. 01-06-2012 07:24 PM

I was just reiterating what you said, really, while adding another link with a slightly broader focus than yours, and a scripting example.

We agree that arrays are the way to go here, certainly. Any time you have a list of related strings, such as file names, you should be using an array for it.

More help on arrays here:
http://mywiki.wooledge.org/BashGuide/Arrays
http://www.tldp.org/LDP/abs/html/arrays.html


All times are GMT -5. The time now is 08:31 AM.