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