Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm using du to get the file size of the result archive in a packager script:

> du -smh archive.zip
51M    archive.zip

I'd like to assign just the 51M part to a variable, to be able to print:

Archive size: 51M

How can I do that?

share|improve this question
add comment

3 Answers

up vote 4 down vote accepted

You can do it like so:

$ variable=$(du -smh archive.zip | awk '{print $1}')

Details

awk will parse the output breaking it up into columns. You want just the results from column #1. The $( .. ) code will run a command and return its results.

share|improve this answer
    
Works like a charm, thanks, for the explanation in particular! –  Benjamin Oct 6 '13 at 16:51
1  
@Benjamin if this answered your question, please mark it as accepted. That's the way to say thanks on the stack exchange sites. –  terdon Oct 6 '13 at 17:04
    
@terdon I quite know that, but had to wait for 10 minutes before the system allowed me to accept the answer! –  Benjamin Oct 6 '13 at 17:07
    
@Benjamin Fair enough, sorry. I hadn't seen your profile and thought you were new to SE in general. –  terdon Oct 6 '13 at 17:11
    
@terdon No worries, that's definitely annoying when people get their answer and walk away! –  Benjamin Oct 6 '13 at 17:24
add comment

Awk is a bigger hammer than you need, use a knife and cut,

variable=$(du -smh archive.zip | cut -f1 )
share|improve this answer
add comment

Or use the stat program, if it's available (usually on Linux by default). No human-readable K/M/G conversion, but it also doesn't require anything else to get just the number / has nice formatting options:

sauer@humpy:~$ stat -c "%s" /etc/passwd
2302
sauer@humpy:~$ stat -c "%n size: %s bytes" /etc/passwd /etc/shadow
/etc/passwd size: 2302 bytes
/etc/shadow size: 1389 bytes
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.