On my bash script, I try to extend my bashrc, with the following lines :

        to_print="alias $nom_machine='ssh $nom_machine'"
        echo -e "$to_print" >> "$target_file"

When executed, I got an error :

 ~/.bashrc: No such file or directory

But the file exists, it is 236 lines :

$ cat ~/.bashrc | wc -l

What is wrong on my script ?

I am on linux ubuntu 14.05

  • Invoke foo="~/.bashrc"; set -x. Then cat ~/.bashrc > /dev/null and cat "$foo" > /dev/null – and you will see the difference. To revert: set +x; unset foo. – Kamil Maciorowski Dec 29 '16 at 20:00

According to this source (https://askubuntu.com/questions/510216/trouble-using-cd-command-with-or-home-in-bash-scripting), you should use:

eval echo -e "$to_print" >> "$target_file"

The reason is given as

The problem is the tilde expansion happens before variable expansion


The ~ (tilde) doesn't always behave as you would expect it to when used in a script or within quotes (I wouldn't guarantee that cat "~/.bashrc" behaves the same), I would recommend preferring ${HOME} (with or without braces) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.