Xuteng echo "something" > > / etc / privilegedFile does not work

Keywords: sudo Linux xml encoding

This is a very simple question about sudo permission in Linux, at least it should be.

Many times, I just want to append some content to / etc/hosts or similar files, but I can't do it in the end, because even if I use root, I can't use > and > > at the same time.

Is there a way to make this work without su or sudo su becoming root?

#1 building

I'll note that, out of curiosity, you can also refer to heredoc (for chunks):

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"

#2 building

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

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

#3 building

Use The answer to Yoo , put it in ~ /. 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' / etc / apt / sources. List

Editor:

A more complete version that allows you to pipe input or redirect from a file and includes the - a switch to turn off additional features (enabled 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
}

#4 building

Can you change the ownership of the file, then attach it using cat > > and change it back?

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

Is something like this suitable for you?

#5 building

It works for me: the original command

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

Work instruction

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

Posted by PHPist on Fri, 10 Jan 2020 07:03:46 -0800