problem with alias being interpreted in command arguments

I have the following alias:

alias mv='mv -i'
alias git='LANG=en_US git '

then when I do a git mv command the mv is interpreted as mv -i:

$ git mv a b
error: unknown switch `i'

I would like the alias to apply only if it is a bash command

Versions:

  • Ubuntu 16.04.3 LTS
  • GNU bash, version 4.3.48(1)
  • git version 2.7.4 (also I don’t think it’s linked to git)

Notes:

  • git mv a b works
  • unaliasing git also works git mv a b
Asked By: jo_

||

Since git is an alias ending with a space, bash performs alias expansion on the word immediately after it:

$ alias mv='mv -i'
$ alias git=': git '
$ set -x
$ git mv
+ : git mv -i

From the docs:

If the last character of the alias value is a blank, then the next
command word following the alias is also checked for alias expansion.

Make git an alias without the space:

alias git='LANG=en_US git'

Note that:

The first word of the replacement text is tested for aliases, but a
word that is identical to an alias being expanded is not expanded a
second time. This means that one may alias ls to ls -F, for
instance, and Bash does not try to recursively expand the replacement
text.

So, you don’t need git there.

Answered By: muru
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.