LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Simple Shell Script is b0rked! (https://www.linuxquestions.org/questions/linux-newbie-8/simple-shell-script-is-b0rked-725919/)

r00tb00t 05-14-2009 07:48 AM

Simple Shell Script is b0rked!
 
Hey Users,


This simple shell scripts looks through all the sub folders in the given directory and in each sub folder is 2 text files, it counts how many lines are in each file and how many directories where accessed but it reports back all zeros (0)?

Code:

#!/bin/sh

f=0
d=0
u=0
t=0
x=0

find /path/to/my/folder -maxdepth 1 -type d | while read FOLDER; do
        f=`expr $f + 1`
        if [ -f $FOLDER/domains ]; then
                x=`wc -l $FOLDER/textfile1 | awk '{print $1}'`
                d=`expr $d + $x`
        fi
        if [ -f $FOLDER/urls ]; then
                x=`wc -l $FOLDER/textfile2 | awk '{print $1}'`
                u=`expr $u + $x`
        fi
done

t=`expr $d + $u`

echo "Number of folders: $f"
echo "Number of lines in textfile1: $d"
echo "Number of lines in textfile2: $u"
echo "Total number of lines for both text files: $t"
echo "$x"

When i run this test script it get the following output:
Code:

[hades@hades ~]$ sh tester
Number of folders: 0
Number of lines in textfile1: 0
Number of lines in textfile2: 0
Total number of lines in both text files: 0
0
[hades@hades ~]$

I am confused, it lookes ok to me but I'm not very good at these things?

colucix 05-14-2009 08:03 AM

The pipe after the find command executes the loop into a subshell. After the subshell terminates all the variables local to the subshell itself are lost. You have to execute the while loop without calling a new subshell. One way is:
Code:

while read FOLDER
do
  <your commands here>
done < <(find /path/to/my/folder -maxdepth 1 -type d)

where the syntax <(command) means "process substitution".

chrism01 05-14-2009 07:24 PM

Alternatively use a for loop
Code:

for file in `find /path/to/my/folder -maxdepth 1 -type d`
do
    blah
done

which I find easier to read

ghostdog74 05-14-2009 07:34 PM

Quote:

Originally Posted by chrism01 (Post 3541215)
Alternatively use a for loop
Code:

for file in `find /path/to/my/folder -maxdepth 1 -type d`
do
    blah
done

which I find easier to read

set IFS for directories with spaces....or use while read loop


All times are GMT -5. The time now is 07:40 PM.