Single command to create a file and set its permission Single command to create a file and set its permission unix unix

Single command to create a file and set its permission


install -m 777 /dev/null filename.txt


For bash, simply use chmod with file redirection and history expansion:

chmod 777 filename.txt>>!#:2

For ksh and zsh you have to drop the history expansion (as shown above, there may be other ways) and use:

chmod 644 filename>>filename

For scripts of any shell you don't have (and really don't need) history expansion so use the above there as well.


First of all, you should NEVER be setting anything to 777 permissions. This is a huge security problem and there just isn't any need for it. For the purposes of this question I will assume you want to create a file with more secure permissions than the defaults, say 600.

There is not a one stop way to safely create AND change the permissions of a file using most bash tools. Even the tricky redirection trick in Paul's answer actually momentarily creates a file with default permissions before resetting them. All new files get created with whatever the system umask value is set too unless the creating program sends very specific requests to the operating system at the time of node creation. A mask of 133 is common, meaning your files get created with 644 permissions out of the box.

Besides using the chmod command to set the file permissions after you create a file, you can also tell the system what defaults you want using the umask command.

$ umask 077$ touch test_file$ ls -l test_file-rw------- 1 user group 0 Jan 24 22:43 test_file

You will note the file has been created with 600 permissions.

This will stay in effect for all commands run in a shell until you either close that shell or manually set another value. If you would like to use this construct to run a single command (or even a small set of them) it can be useful to isolate the commands in a subshell

$ (umask 077 ; touch test_file)

Note that anything else you put inside the parens will use that umask but as soon as you close it, you are back in your previous environment.