Reputation: 41
#!/bin/bash
set_bash_profile()
{
local bash_profile="$HOME/.profile"
if [[ -w $bash_profile ]]; then
if (grep 'MY_VAR' $bash_profile 2>&1); then
sed -i '/MY_VAR/d' $bash_profile
fi
echo "export MY_VAR=foo" >>$bash_profile
fi
}
set_bash_profile
Here is the first run:
bash-4.1$ ./set_bash.sh
No output --which is great! And cat
shows export MY_VAR=foo
was appended to the file. But when executing a second time, I want sed
to silently edit $bash_profile
without outputting the matching string, like it does here:
bash-4.1$ ./set_bash.sh
export MY_VAR=foo
Upvotes: 0
Views: 525
Reputation: 141493
You get the output from grep
on grep 'MY_VAR' $bash_profile 2>&1
. grep outputs the matched line in your profile:
export MY_VAR=foo
on stdout. The 2>&1
only forwards stderr to stdout. It's good to use -q
option with grep. Also the subshell (...)
around the grep is not needed. Try this:
#!/bin/bash
set_bash_profile()
{
local bash_profile="$HOME/.profile"
if [ -w $bash_profile ]; then
if grep -q 'MY_VAR' $bash_profile; then
sed -i '/MY_VAR/d' $bash_profile
fi
echo "export MY_VAR=foo" >>$bash_profile
fi
}
set_bash_profile
Upvotes: 1