0

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.

Ingrid
  • 741
  • 2
  • 8
  • 15
  • 3
    What command are you running with `nuhup`? Please include the full command-line and the full shell script (with all irrelevant parts removed) in the question. – pts May 19 '14 at 18:11
  • 2
    What are you *really* trying to do? This seems a bit X-Y-ish to me... – twalberg May 19 '14 at 18:24
  • It is generally best to include option arguments like `-l` before the non-option arguments like `$direc`. On Linux, both will work; anywhere not using GNU `ls` (or, more generally, the GNU `getopt()` or `getopt_long()` functions in the commands), it won't work unless options precede non-options. It is also generally best to use `var=$(…)` instead of ``var=`…` ``. – Jonathan Leffler May 19 '14 at 18:33
  • By default `nohup` will send standard output to `nohup.out`. If you are trying to use `nohup` within variable assignments, well you guess it right. The output will be redirected to `nohup.out`. – alvits May 19 '14 at 18:41
  • Note [How to list one filename per output line in Linux](http://stackoverflow.com/questions/3886295/how-do-i-list-one-filename-per-output-line-in-linux), and [Why you shouldn't parse the output of ls(1)](http://mywiki.wooledge.org/ParsingLs) referenced from there. [Why can't I use Unix `nohup` with a `for` loop?](http://stackoverflow.com/questions/3099092/why-cant-i-use-unix-nohup-with-bash-for-loop/3099107#3099107) may help; `nohup` takes a command and its arguments, not a fragment of shell script. You can use `nohup sh -c "…fragment of shell script…"`; that's a command and its arguments. – Jonathan Leffler May 19 '14 at 18:55

1 Answers1

1

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249