3

I was trying to have the output of a command as a target of redirection like this:

echo .envrc >> $(git config --global core.excludesfile)

But I get this error instead, where ~/.gitignore_global is the output of git config --global core.excludesfile.

bash: ~/.gitignore_global: No such file or directory

I was able to get it working using eval:

eval "echo .envrc >> $(git config --global core.excludesfile)"

Why didn't it work previously and is there a better way?

2

The problem is that the global git config contains a literal ~ (tilde) which is not interpreted by the shell when emitted as the result of a command substitution. Your global git config likely contains the following:

[core]
    excludesfile = ~/.gitignore_global

Your first command is the equivalent of the following construct, which uses single quotes to prevent shell interpretation of the ~ character:

echo .envrc >> '~/.gitignore_global'

Using eval fixes this because it causes (re-)intepretation of its string argument (in this case, the exact line above), including tilde expansion, which results in the expected command:

echo .envrc >> /home/your_user/.gitignore_global

Another way to fix this is to ensure the value in your global git config is a full path:

git config --global core.excludesfile ~/.gitignore_global

In this case, the shell will expand ~ to /home/your_user, so the contents of your global git config file will read something like:

[core]
    excludesfile = /home/your_user/.gitignore_global
1

It's better not to use tildas like this outside of an interactive shell. (Shell scripts usually use the $HOME environment variable). If you must, the better way is to do the expansion safely and that isn't easy: https://stackoverflow.com/questions/3963716/how-to-manually-expand-a-special-variable-ex-tilde-in-bash/29310477#29310477

If it's just a one-time command, and you know what git config --global core.excludesfile evaluates to and that it's safe to eval that, then your solution is fine.

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.