0

I'm attempting to write a bash script named updateFile.sh. It's currently as follows:

function insertIntoFile(){
    local variable=$1
    local target=$2
    echo "${variable}" | tee -a "${target}";
}

insertIntoFile "export/ foo=bar" "~/.bash_profile"

Running bash -x ./updateFile.sh

For output, I get...

...
+ echo 'export/ foo=bar'
+ tee -a '~/.bash_profile'
export/ foo=bar

however, when I cat ~/.bash_profile

It's still empty of the given string.

I've tried the export without the slash, so I know that's not it, and I've dug through stack overflow, and everything I've seen seems to indicate that this should work, yet I don't see why it's not or how to fix it.

lilHar
  • 1,735
  • 3
  • 21
  • 35

1 Answers1

1

As Inian commented, your use of tilde inside double quotes:

insertIntoFile "export/ foo=bar" "~/.bash_profile"

suffers from the surprise of ~ not being expanded inside double quotes. Use the $HOME variable or remove the double quotes:

insertIntoFile "export/ foo=bar" "$HOME/.bash_profile"

or

insertIntoFile "export/ foo=bar" ~/.bash_profile

I would additionally recommend the use of printf over echo, since various implementations of echo might attempt to parse (read: mangle) a "$variable" value that starts with -n or -e. Change this line:

echo "${variable}" | tee -a "${target}";

to this:

printf '%s\n' "${variable}" | tee -a "${target}";
Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38