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
Author by
siliconpi
Updated on October 31, 2020Comments
-
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 over 12 yearsAnd drop these into a shell function so that you can execute it "from the command line directly".
-
Basile Starynkevitch over 12 yearsBut didn't he tell he "can't use a script" (I didn't understood why)?
-
another.anon.coward over 12 yearsI 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 over 12 yearsHi - can you revise your answer to include chgrp
stat -c %G originalfile
newfile -
siliconpi over 12 yearsHi Māris - why did you remove the access permissions copying?