Create a new empty file from linux command line with same permissions and ownership?

57,113

Solution 1

touch newfile
chmod `stat -c %a originalfile` newfile
chown `stat -c %U originalfile`:`stat -c %G originalfile` newfile

Solution 2

Use

touch newfile
chmod --reference=oldfile newfile
chown --reference=oldfile newfile

Solution 3

cp --attributes-only --preserve=ownership

Solution 4

Use the touch command.

http://www.computerhope.com/unix/utouch.htm

Share:
57,113
siliconpi
Author by

siliconpi

Updated on October 31, 2020

Comments

  • siliconpi
    siliconpi over 3 years

    I need to create a new empty file with the same permissions and ownership (group and user) as the source, kind of like how cp -p FILE1 FILE1.bak works but without actually copying the contents.

    I know I can empty out the contents later on, but that seems wasteful.

    I cant use a script - the solution must run from the command line directly.

  • Noufal Ibrahim
    Noufal Ibrahim over 12 years
    And drop these into a shell function so that you can execute it "from the command line directly".
  • Basile Starynkevitch
    Basile Starynkevitch over 12 years
    But didn't he tell he "can't use a script" (I didn't understood why)?
  • another.anon.coward
    another.anon.coward over 12 years
    I think "chown `stat -c %U originalfile` newfile" should be "chown `stat -c %U originalfile`:`stat -c %G originalfile` newfile" or "chgrp `stat -c %G originalfile` newfile" after chown. In the current solution group permissions are not being considered
  • siliconpi
    siliconpi over 12 years
    Hi - can you revise your answer to include chgrp stat -c %G originalfile newfile
  • siliconpi
    siliconpi over 12 years
    Hi Māris - why did you remove the access permissions copying?