Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the file size on Unix in a Makefile?

I would like to implement this as a Makefile task:

# step 1:
curl -u username:password -X POST \
  -d '{"name": "new_file.jpg","size": 114034,"description": "Latest release","content_type": "text/plain"}' \
  https://api.github.com/repos/:user/:repo/downloads

# step 2:
curl -u username:password \
-F "key=downloads/octocat/Hello-World/new_file.jpg" \
-F "acl=public-read" \
-F "success_action_status=201" \
-F "Filename=new_file.jpg" \
-F "AWSAccessKeyId=1ABCDEF..." \
-F "Policy=ewogIC..." \
-F "Signature=mwnF..." \
-F "Content-Type=image/jpeg" \
-F "file=@new_file.jpg" \
https://github.s3.amazonaws.com/

In the first part however, I need to get the file size (and content type if it's easy, not required though), so some variable:

{"name": "new_file.jpg","size": $(FILE_SIZE),"description": "Latest release","content_type": "text/plain"}

I tried this but it doesn't work (Mac 10.6.7):

$(shell du path/to/file.js | awk '{print $1}')

Any ideas how to accomplish this?

like image 271
Lance Avatar asked Dec 01 '25 09:12

Lance


2 Answers

If you have GNU coreutils:

FILE_SIZE=$(stat -L -c %s $filename)

The -L tells it to follow symlinks; without it, if $filename is a symlink it will give you the size of the symlink rather than the size of the target file.

The MacOS stat equivalent appears to be:

FILE_SIZE=$(stat -L -f %z)

but I haven't been able to try it. (I've written this as a shell command, not a make command.) You may also find the -s option useful:

Display information in "shell output", suitable for initializing variables.

like image 66
Keith Thompson Avatar answered Dec 04 '25 16:12

Keith Thompson


For reference, an alternative method is using du with -b bytes output and -s for summary only. Then cut to only keep the first element of the return string

FILE_SIZE=$(du -sb $filename | cut -f1)

This should return the same result in bytes as @Keith Thompson answer, but will also work for full directory sizes.

Extra: I usually use a macro for this.

define sizeof
    $$(du -sb \
    $(1) \
    | cut -f1 )
endef

Which can then be called like,

$(call sizeof,$filename_or_dirname)
like image 43
edmundoferreira Avatar answered Dec 04 '25 17:12

edmundoferreira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!