Single command to create a file and set its permission

55,204

Solution 1

install -m 777 /dev/null filename.txt

Solution 2

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.

Solution 3

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.

Solution 4

If you want to create the file not just empty but with content and mode at the same time you can use process substitution with install in bash:

install -m 755 <(echo commands go here) newscript

<() places the output into a temporary file (Process-Substitution)

Solution 5

You can create your own command:

create () {
    touch "$1"
    chmod "$2" "$1"
}

create filename.ext 644
Share:
55,204
Admin
Author by

Admin

Updated on July 08, 2022

Comments

  • Admin
    Admin almost 2 years

    I am using the following 2 commands to create a 0B file and set its extn to 644

    touch filename.ext
    chmod 777 filename.txt
    

    My question is that whether there is any single command in unix (korn shell) that will do the two things together that is to say create a 0B fil with desired permission?