0

I am writing into a file with sudo tee, but I don't like that it prints everything on my terminal. But I like that it overwrites whatever is in the file with each script run.

I have tried using cat, but it just reads the file and doesn't overwrite or edit if there are changes to the file, and it still prints to the terminal. How can I use cat to write into a file, including new changes.

Here's an example:

sudo tee /etc/kibana/kibana.yml << EOF
server.port: 5601
elasticsearch.hosts: ["http://${IP}:9200"]
EOF

With the above example, whenever the value of IP changes, the file is updated when I run my script.

sudo cat /etc/kibana/kibana.yml << EOF
server.port: 5601
elasticsearch.hosts: ["http://${IP}:9200"]
EOF

With the above cat example, even when the value of the ip changes, the file doesn't update. It just reads the existing file and prints to the terminal

How can I use cat to properly write into a file, including new changes and not print to the terminal?

eme
  • 45
  • 5
  • See this question: https://stackoverflow.com/questions/2953081/how-can-i-write-a-heredoc-to-a-file-in-bash-script – Ionuț G. Stan Sep 20 '22 at 11:47
  • `cat` doesn't take an argument to specify an output file, and the whole point of using `sudo tee` is to use elevated permissions that you don't get with `sudo cat > file`. You could do `sudo sh -c 'cat input > output'`, but it would be easier to do `sudo tee /etc/kibana/kibana.yml > /dev/null << EOF` – William Pursell Sep 20 '22 at 11:53
  • `tee` doesn't "print to the command line". It prints to the terminal. The command line is the interface you use to interact with the shell, while the terminal is the physical (or virtual) device on which the data is displayed. – William Pursell Sep 20 '22 at 11:54

1 Answers1

1

To suppress the output of tee, just redirect it:

sudo tee /etc/kibana/kibana.yml > /dev/null << EOF
server.port: 5601
elasticsearch.hosts: ["http://${IP}:9200"]
EOF

If you want to use cat, you'll need to wrap it to get elevated permissions for the redirect:

sudo sh -c 'cat > /etc/kibana/kibana.yml' << EOF
server.port: 5601
elasticsearch.hosts: ["http://${IP}:9200"]
EOF

But the tee is preferred.

William Pursell
  • 204,365
  • 48
  • 270
  • 300