sudo bash -c gave permission denied

0

In my linux (centos 7), there are 2 users A (normal user) and B (belongs to wheel group). I am trying to change User A's .bash_profile file by running the following command with user B.

./test.sh /home/a/.bash_profile "export something"

#!/bin/bash

set -o errexit

filePath=${1};
content=${2};

result=`sudo grep "$content" $filePath || true`\
if [[ -z $result ]] || [[ $result == \#* ]]; then
    echo "inside the first if";
    sudo sh -c "$(sed '$a\' ${filePath} > ${filePath}.bak)";
    sudo sh -c "$(echo $content >> ${filePath}.bak)";
    sudo rm -fr ${filePath};
    sudo mv ${filePath}.bak ${filePath};
fi

However it gave the following error:

/home/a/.bash_profile.bak: Permission denied

st.

Posted 2017-02-05T12:02:29.023

Reputation: 3

Answers

0

You don't need $() operator in sudo sh -c ... commands.

When you use this operator for sed '$a\' ${filePath} > ${filePath}.bak then sed and redirection to file > commands are first executed under user b rights, which are insufficient for writing. And only after that sudo sh -c is performed upon the output of the previous commands.

Use sudo sh -c "sed ...", and sudo sh -c "echo ..." instead.

Oleg Bolden

Posted 2017-02-05T12:02:29.023

Reputation: 1 507

it says "sed: -e expression #1, char 1: unterminated address regex" – st. – 2017-02-06T09:55:27.397

SED doesn't understand what you want to do. As I can see you are trying to add something in the end of the ${filePath}, but you add nothing. – Oleg Bolden – 2017-02-06T10:05:56.650

Actually what I want to do is that with user B add new line char end of A's .bash_profile if new line char does not exist. Then add a new content at the end of A's .bash_profile. While doing this back up the original file in case. – st. – 2017-02-06T11:34:50.037

To add a newline use '$a' regexp – Oleg Bolden – 2017-02-06T13:17:40.760

Dollar sign should be escaped with \ in the regex above. If you do not escape it bash considers it as a variable $a and tries to substitute it with its value. – Oleg Bolden – 2017-02-06T13:32:40.547