I don't know who needs to hear this, but the most secure way to create a file with restricted permissions is NOT to use chmod after creating the file:
# ⚠️ Do NOT do this! ⚠️
echo "${SECRET}" > secret.txt
# Between these two commands the secret is world-readable
chmod 400 secret.txt
Instead, you should use umask while creating the file, like this:
# ✅ This is secure
(umask 077; echo "${SECRET}" > secret.txt)
The latter version ensures that the file is "born" secure because of the preceding umask command. Specifically, the umask 077 command ensures that any files created within the subshell (i.e. inside the parentheses) have all group and "other" permissions set to 0 (i.e. not readable/writable/executable).
For example, this even works with your editor, too! You can create a file with your editor like this:
(umask 077; vi secret.txt)
… and any file you create with your editor while the umask is in effect will also be "born" secure.
You typically always want to set umask inside of a subshell, like this:
(umask 077; …)
… because this ensures that the file creation mask is restored to its original value once the subshell completes. If you don't use a subshell then it's much more complicated and error-prone to correctly restore the file creation mask.