Search code examples
cshelllsnohup

ls not working well with nohup


I want to list the number of files in a directory in shell-script. This command works well:

let number_of_files=`ls $direc -l| wc -l`

My problem is that when I use this command with nohup, it doesn't work well.

The same happens when trying to get a file:

file_name=` ls -1 $direc | head -$file_number | tail -1`

Do you know any other option to do it?

I know that in c there is a function:

num_of_files=scandir(directory,&namelist,NULL,NULL);

I also include the full command-line:

nohup sh script_name.sh > log.txt &

Do you know any other way in shell-script that works well with nohup?

Thanks.


Solution

  • Try something like this,

    NUMBER_OF_FILES=$(find . -maxdepth 1 -type f | wc -l)
    echo $NUMBER_OF_FILES
    

    That is find (from the current directory) to a max depth of 1 (e.g. the current directory only) everything that is of type "file", and then count the number of lines. Finally, assign the result of that to NUMBER_OF_FILES.