LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
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, 08: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 08:23 AM.
 
Old 04-04-2013, 08:36 AM   #2
acid_kewpie
Moderator
 
Registered: Jun 2001
Location: UK
Distribution: Gentoo, RHEL, Fedora, Centos
Posts: 43,417

Rep: Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985
Code:
num=$(ls -l|wc -l)
echo $num
if [[ $num == 0 ]]
note that whitespace REALLY REALLY matters here.
 
Old 04-04-2013, 10:03 AM   #3
Habitual
LQ Veteran
 
Registered: Jan 2011
Location: Abingdon, VA
Distribution: Catalina
Posts: 9,374
Blog Entries: 37

Rep: Reputation: Disabled
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 06:01 PM.
 
Old 04-04-2013, 08:28 PM   #4
chrism01
LQ Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Rocky 9.2
Posts: 18,362

Rep: Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751
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, 12:33 AM   #5
grail
LQ Guru
 
Registered: Sep 2009
Location: Perth
Distribution: Manjaro
Posts: 10,008

Rep: Reputation: 3193Reputation: 3193Reputation: 3193Reputation: 3193Reputation: 3193Reputation: 3193Reputation: 3193Reputation: 3193Reputation: 3193Reputation: 3193Reputation: 3193
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, 09:13 AM   #6
Habitual
LQ Veteran
 
Registered: Jan 2011
Location: Abingdon, VA
Distribution: Catalina
Posts: 9,374
Blog Entries: 37

Rep: Reputation: Disabled
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, 10: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 10:53 AM. Reason: Added 'then' :)
 
Old 04-05-2013, 10:38 AM   #8
Habitual
LQ Veteran
 
Registered: Jan 2011
Location: Abingdon, VA
Distribution: Catalina
Posts: 9,374
Blog Entries: 37

Rep: Reputation: Disabled
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 08:49 AM. Reason: past tense of 'take care'
 
Old 04-07-2013, 09:02 PM   #9
chrism01
LQ Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Rocky 9.2
Posts: 18,362

Rep: Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751
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 09:04 PM.
 
Old 04-08-2013, 02:16 AM   #10
acid_kewpie
Moderator
 
Registered: Jun 2001
Location: UK
Distribution: Gentoo, RHEL, Fedora, Centos
Posts: 43,417

Rep: Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985Reputation: 1985
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, 03:51 PM   #11
Habitual
LQ Veteran
 
Registered: Jan 2011
Location: Abingdon, VA
Distribution: Catalina
Posts: 9,374
Blog Entries: 37

Rep: Reputation: Disabled
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, 05:59 PM   #12
chrism01
LQ Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Rocky 9.2
Posts: 18,362

Rep: Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751
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, 04:50 PM   #13
David the H.
Bash Guru
 
Registered: Jun 2004
Location: Osaka, Japan
Distribution: Arch + Xfce
Posts: 6,852

Rep: Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037
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 05:00 PM. Reason: as stated
 
  


Reply



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 03:41 AM
[SOLVED] Sed: assigning its output to a variable. stf92 Linux - Newbie 3 02-04-2011 12:38 AM
Assigning variable is messing up voldemort Programming 1 11-05-2010 02:26 PM
Trouble assigning value to variable with fatsheep Programming 1 11-07-2006 07:44 PM
assigning commands to a variable aunquarra Linux - General 5 01-04-2006 07:58 AM

LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie

All times are GMT -5. The time now is 02:55 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
Open Source Consulting | Domain Registration