LinuxQuestions.org
Latest LQ Deal: Linux Power User Bundle
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!

Notices


Reply
  Search this Thread
Old 04-04-2013, 09:19 AM   #1
Saratha
LQ Newbie
 
Registered: Mar 2013
Posts: 4

Rep: Reputation: Disabled
Assigning the count to a variable


Hi,

I need to count the number of Files in a folder and then assign it to a variable.I need to print the assigned variable.

num = ls -l|wc -l
echo $num
if[$num == 0]

In if condition i get $num as blank.

Could you please help me to solve it.

Thanks

Last edited by Saratha; 04-04-2013 at 09:23 AM.
 
Old 04-04-2013, 09:36 AM   #2
acid_kewpie
Moderator
 
Registered: Jun 2001
Location: UK
Distribution: Gentoo, RHEL, Fedora, Centos
Posts: 43,417

Rep: Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974
Code:
num=$(ls -l|wc -l)
echo $num
if [[ $num == 0 ]]
note that whitespace REALLY REALLY matters here.
 
Old 04-04-2013, 11:03 AM   #3
Habitual
LQ Addict
 
Registered: Jan 2011
Posts: 7,678
Blog Entries: 10

Rep: Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078
Saratha:
Excuse me, I don't mean to hijack your thread, but I wonder if Chris can elaborate on the use of "==" for testing here?
It appears by Saratha's snippet that (in essence) IF "$num" is equal to exactly "0" ; then do_work; else go_home; fi

What's the benefit of say
Code:
if [[ -n $num ]] ; then do_work; else go_home; fi
? Would that work?

so, from some cursory peeking at man bash it appears that
Code:
       -n string
              True if the length of string is non-zero.
string of "0" vs empty ("")space?

num=$(ls -l|wc -l) here in an empty directory produces
1
so
Code:
[[ $num == 0 ]]
will never happen?

I guess the question to ask is are we testing for empty "$num" using "num=$(ls -l|wc -l)"?
because
(ls -l|wc -l) gives us 1
(ls *|wc -l) gives us 0


Am I confused? Definitely.
I don't understand when one should use
Code:
[[ $variable == 0 ]] or [[ -n $variable ]]
and I'll probably go "oh snap!" 5 seconds after posting this

and now back to our Polite New Member, Saratha...

Last edited by Habitual; 04-04-2013 at 07:01 PM.
 
Old 04-04-2013, 09:28 PM   #4
chrism01
LQ Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Centos 6.8, Centos 5.10
Posts: 17,260

Rep: Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328
If I understand you (Habitual) correctly, the point of not using -n is because even in an empty dir, wc returns '0' which has length(!) eg
Code:
# tmpx is an empty dir ...
cd tmpx
v1=$(ls|wc -l)
if [[ -n $v1 ]]
then
    echo "v1 $v1 has len"
fi

# output is
v1 0 has len
 
Old 04-05-2013, 01:33 AM   #5
grail
LQ Guru
 
Registered: Sep 2009
Location: Perth
Distribution: Manjaro
Posts: 9,425

Rep: Reputation: 2826Reputation: 2826Reputation: 2826Reputation: 2826Reputation: 2826Reputation: 2826Reputation: 2826Reputation: 2826Reputation: 2826Reputation: 2826Reputation: 2826
It would appear we are forgetting the option of having hidden files / directories. Your standard ls will not show hidden items and so the directory may indeed not be empty.

Maybe this old question can help with some alternatives:

http://www.linuxquestions.org/questi...or-not-891606/
 
Old 04-05-2013, 10:13 AM   #6
Habitual
LQ Addict
 
Registered: Jan 2011
Posts: 7,678
Blog Entries: 10

Rep: Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078
Quote:
Originally Posted by chrism01 View Post
If I understand you (Habitual) correctly, the point of not using -n is because even in an empty dir, wc returns '0' which has length(!) eg
Code:
# tmpx is an empty dir ...
cd tmpx
v1=$(ls|wc -l)
if [[ -n $v1 ]]
then
    echo "v1 $v1 has len"
fi

# output is
v1 0 has len
Chris: I just want to know an example of when to use "== 0" or when to use '"-n "$VARIABLE"' and how to test for an empty directory.

You didn't quote your variable, how come?
Code:
if [[ -n "$v1" ]]
The output with or without quotes is identical, I just thought it is 'good form' to always quote your(?) variables and use them in upper case.
I also only know that the OP's code snippet begged me to ask "What are you trying to do there?"

I am an odd duck and I don't really have anything to contribute to this discussion except inquiries into my own ignorance.
and I love to code.

Thanks.
 
Old 04-05-2013, 11:07 AM   #7
shivaa
Senior Member
 
Registered: Jul 2012
Location: Grenoble, Fr.
Distribution: Sun Solaris, RHEL, Ubuntu, Debian 6.0
Posts: 1,800
Blog Entries: 4

Rep: Reputation: 286Reputation: 286Reputation: 286
OP:
The condition ls -l | wc -l will never return a 0, even for empty directory, it will return 1, so the if [[ $var == 0 ]] condition will never execute.
Code:
~$ mkdir foo
~$ cd foo
~$ ls -l
total 0
~$ ls -l | wc -l
1
You should try like:
Code:
var=$(ls -l | grep -v 'total' | wc -l)
if [[ $var == 0 ]]; then
commands
fi

Last edited by shivaa; 04-05-2013 at 11:53 AM. Reason: Added 'then' :)
 
Old 04-05-2013, 11:38 AM   #8
Habitual
LQ Addict
 
Registered: Jan 2011
Posts: 7,678
Blog Entries: 10

Rep: Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078
Quote:
Originally Posted by shivaa View Post
OP:
The condition ls -l | wc -l will never return a 0
That is exactly the answer I was looking for!

So, if "ls -l | wc -l will never return a 0" then it doesn't matter little what operator is...
but if one knows it will never return 0, then it could be programmatically taken care of.

I am a sick puppy as I find these rudimentary topics on logic intriguing and discussing these techniques inspires me.

I have no idea what the OP intended.

- Thanks Gurus!

Last edited by Habitual; 04-08-2013 at 09:49 AM. Reason: past tense of 'take care'
 
Old 04-07-2013, 10:02 PM   #9
chrism01
LQ Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Centos 6.8, Centos 5.10
Posts: 17,260

Rep: Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328
Re quotes round tested vars; really it depends on how well you know your 'data'. Obviously the most general rule is to use quotes (in case of spaces & other 'odd' chars), but I don't bother unless I know or think I'm going to need to.
It just makes the code 'noisy'.
I'm old school *nix (about 15 yrs usage or so) and never use spaces in filenames etc. OTOH, if you're not the data producer, you may not get a choice eg MS files via Samba.

I'm sure david_the_h would insist on quotes all the time


This leads into the concept of writing shorter/faster code for data processing if you can reasonably rely on the type of values and their range. It may enable you to use shortcuts, rather than always having to use a general soln which will take more (&/or more complex) code, be harder to maintain & take longer to run for instance.
Its really a judgement call
PS Of course you also need good error handling ...

Last edited by chrism01; 04-07-2013 at 10:04 PM.
 
Old 04-08-2013, 03:16 AM   #10
acid_kewpie
Moderator
 
Registered: Jun 2001
Location: UK
Distribution: Gentoo, RHEL, Fedora, Centos
Posts: 43,417

Rep: Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974Reputation: 1974
well it's worth nothing that you'd only need quotes if you're using [ / test. Using [[ wouldn't need them as it tokenizes the variables within bash. Does of course make it bash specific though, so it's not as portable.
 
Old 04-08-2013, 04:51 PM   #11
Habitual
LQ Addict
 
Registered: Jan 2011
Posts: 7,678
Blog Entries: 10

Rep: Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078Reputation: 2078
Quote:
Originally Posted by chrism01 View Post
I'm sure david_the_h would insist on quotes all the time...
PS Of course you also need good error handling ...
Yes, to either|both.

Thanks!
 
Old 04-08-2013, 06:59 PM   #12
chrism01
LQ Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Centos 6.8, Centos 5.10
Posts: 17,260

Rep: Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328Reputation: 2328
Actually, I was first taught to always(!) use [[ ]] on a ksh course, so that's at least 2 shells you can use it in.
 
Old 04-09-2013, 05:50 PM   #13
David the H.
Bash Guru
 
Registered: Jun 2004
Location: Osaka, Japan
Distribution: Debian sid + kde 3.5 & 4.4
Posts: 6,823

Rep: Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958Reputation: 1958
Y'all know me well.

Yes, I would recommend quotes pretty much all the time. Not just because of word-splitting, but because any globbing characters are interpreted too. You could conceivably end up with a list of filenames instead of the string you expected.

The only time I'd feel safe leaving them off is if you know what you're doing and are certain that there's no chance of surprises. Variables that only contain digits, like counters, are generally safe. But even then it never hurts to keep in the habit and use them anyway.

As for the OP topic, parsing ls like this is not generally recommended. Although to be fair the only real danger comes from the rare chance of a name containing a newline. So I wouldn't argue against it for a quick&dirty count, for a real script you should probably use something more robust.

Assuming a single directory with no recursion, a simple loop is all that's required.

Code:
shopt -s dotglob

for fname in *; do
    [[ -f $fname ]] && (( count++ ))
done

echo "$count"
In more advanced cases you may want to load the matching files into an array. That would let you grab the first/last file, for example.

How can I find the latest (newest, earliest, oldest) file in a directory?
http://mywiki.wooledge.org/BashFAQ/003
How can I get the newest (or oldest) file from a directory?
http://mywiki.wooledge.org/BashFAQ/099

(As you can see, the topic is currently split among two pages.)

Edit: I almost forgot about first setting dotglob, to catch the hidden files.

Also, in bash or ksh, you should use ((..)) to evaluate numerical test conditions, instead of the square bracket tests. Use [[..]] for string and file comparisons.

Code:
if (( count == 0 )); then

Last edited by David the H.; 04-09-2013 at 06:00 PM. Reason: as stated
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
assigning value * to variable problem coolpraz Programming 2 01-13-2013 04:41 AM
[SOLVED] Sed: assigning its output to a variable. stf92 Linux - Newbie 3 02-04-2011 01:38 AM
Assigning variable is messing up voldemort Programming 1 11-05-2010 03:26 PM
Trouble assigning value to variable with fatsheep Programming 1 11-07-2006 08:44 PM
assigning commands to a variable aunquarra Linux - General 5 01-04-2006 08:58 AM


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

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration