[bash] sudo echo "something" >> /etc/privilegedFile doesn't work

This is a pretty simple question, at least it seems like it should be, about sudo permissions in Linux.

There are a lot of times when I just want to append something to /etc/hosts or a similar file but end up not being able to because both > and >> are not allowed, even with root.

Is there someway to make this work without having to su or sudo su into root?

This question is related to bash shell scripting permissions sudo

The answer is


Use tee --append or tee -a.

echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list

Make sure to avoid quotes inside quotes.

To avoid printing data back to the console, redirect the output to /dev/null.

echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list > /dev/null

Remember about the (-a/--append) flag! Just tee works like > and will overwrite your file. tee -a works like >> and will write at the end of the file.


The problem is that the shell does output redirection, not sudo or echo, so this is being done as your regular user.

Try the following code snippet:

sudo sh -c "echo 'something' >> /etc/privilegedfile"

The problem is that the shell does output redirection, not sudo or echo, so this is being done as your regular user.

Try the following code snippet:

sudo sh -c "echo 'something' >> /etc/privilegedfile"

The problem is that the shell does output redirection, not sudo or echo, so this is being done as your regular user.

Try the following code snippet:

sudo sh -c "echo 'something' >> /etc/privilegedfile"

The problem is that the shell does output redirection, not sudo or echo, so this is being done as your regular user.

Try the following code snippet:

sudo sh -c "echo 'something' >> /etc/privilegedfile"

The issue is that it's your shell that handles redirection; it's trying to open the file with your permissions not those of the process you're running under sudo.

Use something like this, perhaps:

sudo sh -c "echo 'something' >> /etc/privilegedFile"

The issue is that it's your shell that handles redirection; it's trying to open the file with your permissions not those of the process you're running under sudo.

Use something like this, perhaps:

sudo sh -c "echo 'something' >> /etc/privilegedFile"

The issue is that it's your shell that handles redirection; it's trying to open the file with your permissions not those of the process you're running under sudo.

Use something like this, perhaps:

sudo sh -c "echo 'something' >> /etc/privilegedFile"

The issue is that it's your shell that handles redirection; it's trying to open the file with your permissions not those of the process you're running under sudo.

Use something like this, perhaps:

sudo sh -c "echo 'something' >> /etc/privilegedFile"

sudo sh -c "echo 127.0.0.1 localhost >> /etc/hosts"

sudo sh -c "echo 127.0.0.1 localhost >> /etc/hosts"

sudo sh -c "echo 127.0.0.1 localhost >> /etc/hosts"

sudo sh -c "echo 127.0.0.1 localhost >> /etc/hosts"

Doing

sudo sh -c "echo >> somefile"

should work. The problem is that > and >> are handled by your shell, not by the "sudoed" command, so the permissions are your ones, not the ones of the user you are "sudoing" into.


Doing

sudo sh -c "echo >> somefile"

should work. The problem is that > and >> are handled by your shell, not by the "sudoed" command, so the permissions are your ones, not the ones of the user you are "sudoing" into.


Doing

sudo sh -c "echo >> somefile"

should work. The problem is that > and >> are handled by your shell, not by the "sudoed" command, so the permissions are your ones, not the ones of the user you are "sudoing" into.


Doing

sudo sh -c "echo >> somefile"

should work. The problem is that > and >> are handled by your shell, not by the "sudoed" command, so the permissions are your ones, not the ones of the user you are "sudoing" into.


I would note, for the curious, that you can also quote a heredoc (for large blocks):

sudo bash -c "cat <<EOIPFW >> /etc/ipfw.conf
<?xml version=\"1.0\" encoding=\"UTF-8\"?>

<plist version=\"1.0\">
  <dict>
    <key>Label</key>
    <string>com.company.ipfw</string>
    <key>Program</key>
    <string>/sbin/ipfw</string>
    <key>ProgramArguments</key>
    <array>
      <string>/sbin/ipfw</string>
      <string>-q</string>
      <string>/etc/ipfw.conf</string>
    </array>
    <key>RunAtLoad</key>
    <true></true>
  </dict>
</plist>
EOIPFW"

I would note, for the curious, that you can also quote a heredoc (for large blocks):

sudo bash -c "cat <<EOIPFW >> /etc/ipfw.conf
<?xml version=\"1.0\" encoding=\"UTF-8\"?>

<plist version=\"1.0\">
  <dict>
    <key>Label</key>
    <string>com.company.ipfw</string>
    <key>Program</key>
    <string>/sbin/ipfw</string>
    <key>ProgramArguments</key>
    <array>
      <string>/sbin/ipfw</string>
      <string>-q</string>
      <string>/etc/ipfw.conf</string>
    </array>
    <key>RunAtLoad</key>
    <true></true>
  </dict>
</plist>
EOIPFW"

In bash you can use tee in combination with > /dev/null to keep stdout clean.

 echo "# comment" |  sudo tee -a /etc/hosts > /dev/null

In bash you can use tee in combination with > /dev/null to keep stdout clean.

 echo "# comment" |  sudo tee -a /etc/hosts > /dev/null

Using Yoo's answer, put this in your ~/.bashrc:

sudoe() {
    [[ "$#" -ne 2 ]] && echo "Usage: sudoe <text> <file>" && return 1
    echo "$1" | sudo tee --append "$2" > /dev/null
}

Now you can run sudoe 'deb blah # blah' /etc/apt/sources.list


Edit:

A more complete version which allows you to pipe input in or redirect from a file and includes a -a switch to turn off appending (which is on by default):

sudoe() {
  if ([[ "$1" == "-a" ]] || [[ "$1" == "--no-append" ]]); then
    shift &>/dev/null || local failed=1
  else
    local append="--append"
  fi

  while [[ $failed -ne 1 ]]; do
    if [[ -t 0 ]]; then
      text="$1"; shift &>/dev/null || break
    else
      text="$(cat <&0)"
    fi

    [[ -z "$1" ]] && break
    echo "$text" | sudo tee $append "$1" >/dev/null; return $?
  done

  echo "Usage: $0 [-a|--no-append] [text] <file>"; return 1
}

Using Yoo's answer, put this in your ~/.bashrc:

sudoe() {
    [[ "$#" -ne 2 ]] && echo "Usage: sudoe <text> <file>" && return 1
    echo "$1" | sudo tee --append "$2" > /dev/null
}

Now you can run sudoe 'deb blah # blah' /etc/apt/sources.list


Edit:

A more complete version which allows you to pipe input in or redirect from a file and includes a -a switch to turn off appending (which is on by default):

sudoe() {
  if ([[ "$1" == "-a" ]] || [[ "$1" == "--no-append" ]]); then
    shift &>/dev/null || local failed=1
  else
    local append="--append"
  fi

  while [[ $failed -ne 1 ]]; do
    if [[ -t 0 ]]; then
      text="$1"; shift &>/dev/null || break
    else
      text="$(cat <&0)"
    fi

    [[ -z "$1" ]] && break
    echo "$text" | sudo tee $append "$1" >/dev/null; return $?
  done

  echo "Usage: $0 [-a|--no-append] [text] <file>"; return 1
}

You can also use sponge from the moreutils package and not need to redirect the output (i.e., no tee noise to hide):

echo 'Add this line' | sudo sponge -a privfile

You can also use sponge from the moreutils package and not need to redirect the output (i.e., no tee noise to hide):

echo 'Add this line' | sudo sponge -a privfile

Some user not know solution when using multiples lines.

sudo tee -a  /path/file/to/create_with_text > /dev/null <<EOT 
line 1
line 2
line 3
EOT

Some user not know solution when using multiples lines.

sudo tee -a  /path/file/to/create_with_text > /dev/null <<EOT 
line 1
line 2
line 3
EOT

By using sed -i with $ a , you can append text, containing both variables and special characters, after the last line.

For example, adding $NEW_HOST with $NEW_IP to /etc/hosts:

sudo sed -i "\$ a $NEW_IP\t\t$NEW_HOST.domain.local\t$NEW_HOST" /etc/hosts

sed options explained:

  • -i for in-place
  • $ for last line
  • a for append

By using sed -i with $ a , you can append text, containing both variables and special characters, after the last line.

For example, adding $NEW_HOST with $NEW_IP to /etc/hosts:

sudo sed -i "\$ a $NEW_IP\t\t$NEW_HOST.domain.local\t$NEW_HOST" /etc/hosts

sed options explained:

  • -i for in-place
  • $ for last line
  • a for append

echo 'Hello World' | (sudo tee -a /etc/apt/sources.list)


echo 'Hello World' | (sudo tee -a /etc/apt/sources.list)


How about:
echo text | sudo dd status=none of=privilegedfile
I want to change /proc/sys/net/ipv4/tcp_rmem.
I did:
sudo dd status=none of=/proc/sys/net/ipv4/tcp_rmem <<<"4096 131072 1024000"
eliminates the echo with a single line document


How about:
echo text | sudo dd status=none of=privilegedfile
I want to change /proc/sys/net/ipv4/tcp_rmem.
I did:
sudo dd status=none of=/proc/sys/net/ipv4/tcp_rmem <<<"4096 131072 1024000"
eliminates the echo with a single line document


This worked for me: original command

echo "export CATALINA_HOME="/opt/tomcat9"" >> /etc/environment

Working command

echo "export CATALINA_HOME="/opt/tomcat9"" |sudo tee /etc/environment

This worked for me: original command

echo "export CATALINA_HOME="/opt/tomcat9"" >> /etc/environment

Working command

echo "export CATALINA_HOME="/opt/tomcat9"" |sudo tee /etc/environment

Can you change the ownership of the file then change it back after using cat >> to append?

sudo chown youruser /etc/hosts  
sudo cat /downloaded/hostsadditions >> /etc/hosts  
sudo chown root /etc/hosts  

Something like this work for you?


Can you change the ownership of the file then change it back after using cat >> to append?

sudo chown youruser /etc/hosts  
sudo cat /downloaded/hostsadditions >> /etc/hosts  
sudo chown root /etc/hosts  

Something like this work for you?


Questions with bash tag:

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal? Copy Files from Windows to the Ubuntu Subsystem Docker: How to use bash with an Alpine based docker image? How to print / echo environment variables? Passing bash variable to jq gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now How to check if an environment variable exists and get its value? docker entrypoint running bash script gets "permission denied" Copy Paste in Bash on Ubuntu on Windows How to set env variable in Jupyter notebook How do I disable Git Credential Manager for Windows? How to set aliases in the Git Bash for Windows? MINGW64 "make build" error: "bash: make: command not found" Disable beep of Linux Bash on Windows 10 What does `set -x` do? psql: command not found Mac How do I use a regex in a shell script? nodemon not working: -bash: nodemon: command not found How to open google chrome from terminal? Get Environment Variable from Docker Container How to find files modified in last x minutes (find -mmin does not work as expected) How to pass arguments to Shell Script through docker run How to run C program on Mac OS X using Terminal? Curl command without using cache Running a script inside a docker container using shell script Creating an array from a text file in Bash Bash checking if string does not contain other string How to check if a Docker image with a specific tag exist locally? How do I edit $PATH (.bash_profile) on OSX? Raise error in a Bash script how to wait for first command to finish? I just assigned a variable, but echo $variable shows something else What do $? $0 $1 $2 mean in shell script? How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script How can I remount my Android/system as read-write in a bash script using adb? How to get ip address of a server on Centos 7 in bash Changing an AIX password via script? How to remove last n characters from a string in Bash? Difference between ${} and $() in Bash List file using ls command in Linux with full path

Questions with shell tag:

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied" Interactive shell using Docker Compose How do I use a regex in a shell script? How to pass arguments to Shell Script through docker run Can pm2 run an 'npm start' script Running a script inside a docker container using shell script shell script to remove a file if it already exist Run a command shell in jenkins Raise error in a Bash script I just assigned a variable, but echo $variable shows something else What do $? $0 $1 $2 mean in shell script? How to sort a file in-place How to get a shell environment variable in a makefile? How to read a .properties file which contains keys that have a period character using Shell script Run multiple python scripts concurrently how to check which version of nltk, scikit learn installed? Changing an AIX password via script? Loop through a comma-separated shell variable How to use execvp() List file using ls command in Linux with full path How to use su command over adb shell? Display curl output in readable JSON format in Unix shell script How to check the exit status using an if statement How to solve ADB device unauthorized in Android ADB host device? Redirect echo output in shell script to logfile adb shell su works but adb root does not Run Python script at startup in Ubuntu Copy multiple files from one directory to another from Linux shell Relative paths based on file location instead of current working directory How to Batch Rename Files in a macOS Terminal? Speed up rsync with Simultaneous/Concurrent File Transfers? Multi-line string with extra space (preserved indentation) How to set child process' environment variable in Makefile Get MAC address using shell script How to force 'cp' to overwrite directory instead of creating another one inside? Multiple conditions in if statement shell script How do I change file permissions in Ubuntu How to get key names from JSON using jq Bash: Echoing a echo command with a variable in bash How/When does Execute Shell mark a build as failure in Jenkins? Shell Script: How to write a string to file and to stdout on console?

Questions with scripting tag:

What does `set -x` do? Creating an array from a text file in Bash Windows batch - concatenate multiple text files into one Raise error in a Bash script How do I assign a null value to a variable in PowerShell? Difference between ${} and $() in Bash Using a batch to copy from network drive to C: or D: drive Check if a string matches a regex in Bash script How to run a script at a certain time on Linux? How to make an "alias" for a long path? Scripting Language vs Programming Language Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it? Find multiple files and rename them in Linux Shell script not running, command not found Bash scripting missing ']' PuTTY scripting to log onto host Shell script to capture Process ID and kill it if exist Copy files to network computers on windows command line How to get disk capacity and free space of remote computer Using sed, Insert a line above or below the pattern? How to count objects in PowerShell? Setting a windows batch file variable to the day of the week Add objects to an array of objects in Powershell eval command in Bash and its typical uses Execute command on all files in a directory Counter increment in Bash loop not working if arguments is equal to this string, define a variable like this string How to get the Parent's parent directory in Powershell? Unix - create path of folders and file Adding newline characters to unix shell variables Bash array with spaces in elements Why do you need to put #!/bin/bash at the beginning of a script file? How can I run a function from a script in command line? unix - count of columns in file How to stop a vb script running in windows Increase max execution time for php Purpose of #!/usr/bin/python3 shebang How do I script a "yes" response for installing programs? How do I get cURL to not show the progress bar? Meaning of $? (dollar question mark) in shell scripts How to get the part of a file after the first line that matches a regular expression? What is the $? (dollar question mark) variable in shell scripting? Execute SQL script from command line Test or check if sheet exists Shell script to get the process ID on Linux How do you execute an arbitrary native command from a string? How to delete items from a dictionary while iterating over it? How to run a shell script in OS X by double-clicking? How to pass boolean values to a PowerShell script from a command prompt in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

Questions with permissions tag:

On npm install: Unhandled rejection Error: EACCES: permission denied Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE) ActivityCompat.requestPermissions not showing dialog box PostgreSQL: role is not permitted to log in Android 6.0 multiple permissions Storage permission error in Marshmallow Android M Permissions: onRequestPermissionsResult() not being called pip install failing with: OSError: [Errno 13] Permission denied on directory SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac changing the owner of folder in linux git push: permission denied (public key) Differences between CHMOD 755 vs 750 permissions set How to disable Google asking permission to regularly check installed apps on my phone? npm install errors with Error: ENOENT, chmod Failed to add the host to the list of know hosts Adding Permissions in AndroidManifest.xml in Android Studio? npm throws error without sudo Forbidden You don't have permission to access /wp-login.php on this server Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx---- IIS_IUSRS and IUSR permissions in IIS8 permission denied - php unlink adb remount permission denied, but able to access super user in shell -- android Permissions for /var/www/html Permission denied at hdfs SQL Server 2012 can't start because of a login failure How to set 777 permission on a particular folder? rsync - mkstemp failed: Permission denied (13) MySQL error 1449: The user specified as a definer does not exist ERROR: permission denied for sequence cities_id_seq using Postgres GRANT EXECUTE to all stored procedures ssh "permissions are too open" error SQL Server 2008 R2 Express permissions -- cannot create database or modify users www-data permissions? Why do I get permission denied when I try use "make" to install something? XAMPP permissions on Mac OS X? WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server Chmod 777 to a folder and all contents cd into directory without having permission Trying to SSH into an Amazon Ec2 instance - permission error IIS7 Permissions Overview - ApplicationPoolIdentity How permission can be checked at runtime without throwing SecurityException? ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted How to reset Django admin password? Permission denied when launch python script via bash IIS AppPoolIdentity and file system write access permissions Android: java.lang.SecurityException: Permission Denial: start Intent warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777 How to give credentials in a batch script that copies files to a network location? changing permission for files and folder recursively using shell command in mac How to change permissions for a folder and its subfolders/files in one step?

Questions with sudo tag:

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied How to run SUDO command in WinSCP to transfer files from Windows to linux How to install Intellij IDEA on Ubuntu? pip install: Please check the permissions and owner of that directory How to use sudo inside a docker container? How to fix 'sudo: no tty present and no askpass program specified' error? npm install errors with Error: ENOENT, chmod npm throws error without sudo Is it acceptable and safe to run pip install under sudo? Command not found when using sudo Use sudo with password as parameter How to give a Linux user sudo access? proper way to sudo over ssh How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it? www-data permissions? Copying a local file from Windows to a remote server using scp How to keep environment variables when using sudo How to run script as another user without password? how to run two commands in sudo? Rails: Why "sudo" command is not recognized? Root user/sudo equivalent in Cygwin? sudo in php exec() How does the vim "write with sudo" trick work? How do I use su to execute the rest of the bash script as that user? running a command as a super user from a python script Why does sudo change the PATH? How to pass the password to su/sudo/ssh without overriding the TTY? sudo echo "something" >> /etc/privilegedFile doesn't work How do I use sudo to redirect output to a location I don't have permission to write to?