Search code examples
bashshellack

ack command didn't return output from current directory in bash script


(edited) Let say i have some directory structure like this:

lv1_directory
|  file_contain_word_something.txt
|  lv2_directory

so now i'm at lv2_directory and i have a code like this:

#!/bin/bash
findfile=$(ack -n 'something' . | wc -l)
cd ..
ls
echo $findfile

when i run the script it give me

lv2_directory            file_contain_word_something.txt
0

but if i didn't assign it to variable it work like charm

#!/bin/bash
cd ..
ls
ack -n 'something' | wl -l

it give me

lv2_directory            file_contain_word_something.txt
1

so i have to change it to this to work

#!/bin/bash
findfile=$(ack -n 'something' .. | wc -l)
cd ..
ls  
echo $findfile 

it give me the result i want

lv2_directory            file_contain_word_something.txt
1

How can i use the first script and give me the result i want?


Solution

  • I think the problem here is:

    You are currently inside lv2_directory which DOES NOT HAVE any file which matches the string 'something'. So when you fire ack from this dir itself, you get 0 for number of lines. Then you do cd...

    #!/bin/bash
    findfile=$(ack -n 'something' . | wc -l)
    cd ..
    ls
    echo $findfile
    

    Now, in your next snippet:

    #!/bin/bash
    cd ..
    ls
    ack -n 'something' | wl -l
    

    You are first doing cd, so you are into lv1_directory, which has the file file_contain_word_something.txt. Then you fire your ack. Now it finds something in the txt file and hence, gives you 1 as the output(assuming there's only 1 matching line).