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 w
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)
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.