I'd like to have a file on my computer that stores a particular token (rather than having them just exported to the shell env). As such, I'd like that the token can only be read by sudo, so access to it requires authorisation. How can I write a file that can only be read by sudo?


3 Answers 3


Note that sudo is not synonymous with root/superuser. In fact, sudo command let you execute commands as virtually any user, as specified by the security policy:

$ sudo whoami
$ sudo -u bob whoami

I assume you meant to create a file that only root user can read:

# Create the file
touch file

# Change permissions of the file
# '600' means only owner has read and write permissions
chmod 600 file

# Change owner of the file
sudo chown root:root file

When you need to edit the content of the file:

# Replace 'nano' with your prefered editor
sudo nano file

See how only root can read the file:

$ cat file
cat: file: Permission denied
$ sudo cat file
foo bar baz

Figured it out:

echo 'hello world' > test
sudo chown root test
sudo chmod 600 test
sudo cat test

In another terminal, if you do it without sudo:

> cat test
cat: test: Permission denied
  • 2
    Why do you want the file to be executable by root? Commented Jul 13, 2018 at 9:34
  • 1
    Consider instead applying chmod 600, if nothing else, it's more obvious what the purpose of your file is, when it's non-executable. Commented Jul 13, 2018 at 13:01
  • Good point, updated
    – balupton
    Commented Jul 17, 2018 at 12:49

With tee

$ echo "some text" | sudo tee tmpfile
some text
$ sudo chmod 700 tmpfile 
$ cat tmpfile
cat: tmpfile: Permission non accordée
$ sudo cat tmpfile
some text

For append :

$ echo "text appened" | sudo tee -a tmpfile
$ sudo cat tmpfile
somme text
text appened
$ sudo rm tmpfile

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .