Search code examples
bashshellcattee

use cat to properly write into a file in bash


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?


Solution

  • 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.