views:

78

answers:

3

I want to work on the files generated by the split command. How do I count these files?

I am moving these to a separate directory, so it would help if someone could tell me how to store the output of ls -1|wc -l to a variable in a shell script.

+2  A: 
myvar=`ls -1|wc -l`

or

myvar=$(ls -1|wc -l)

They behave the same way

Hai Vu
$() is preferred.
Dennis Williamson
@Dennis: I agree, however, there are some old borne shell that does not understand $(..)
Hai Vu
+1  A: 

If you surround a command with backticks - `command ` - the command is run and output replaces the quoted text. This is called Command Substitution. So you can store the output of a command in a variable like so:

COUNT=`ls -1|wc -l`

However, you don't have to store the output in a variable. You can use the backticks in the middle of another command. For example:

echo Split made `ls -1|wc -l` files.
Dave Webb
Duh! you are half a minute ahead of me. You need to put in the ending back tick `
Hai Vu
Answers with equal votes are no longer displayed in time order so it doesn't matter who's first any more. But thanks anyway. :-)
Dave Webb
I could ve sworn I was trying the exact same thing and it wasnt working. Thanks!
Kapsh
+1  A: 

all you need to do is:

count=$(ls -l | wc -l)

to store the number of files in the variable count

ennuikiller