if-then-else inside Bash Alias
Solution 1
I would use a function for that, like so:
gitmv()
{
# If in a git repo - call git mv. otherwise- call mv
if [ x`git rev-parse --show-toplevel 2> /dev/null` = x ];
then
mv "$@"
else
git mv "$@"
fi
}
Edit:
alias mv=gitmv
Solution 2
Although jhscheer proposed a much better solution (IMHO), it is still possible to achieve what you were trying to do with only an alias.
Your alias did not work because of the external double quotes, which make git mv
a single token, and you have no git mv
executable. If you remove the external double quotes, your alias should work fine.
By the way, the inner double quotes, in echo "git mv"
are useless, but harmless.
I have no git repository immediately available to test, but I just tried with the following alias:
alias foo='$(if [ x"`pwd`" = x"$HOME" ] ; then echo echo; else echo echo foo; fi)'
Related videos on Youtube
switch87
Updated on September 18, 2022Comments
-
switch87 over 1 year
I am trying to make an alias for
mv
so it does its normal behaviour in normal folders and is replaced bygit mv
inside git repositories. I tried many ways. Theif
statement works, only the commandgit mv
will not run correctly.alias mv='"$( if [ x`git rev-parse --show-toplevel 2> /dev/null` = x ]; echo mv; else echo "git mv"; fi)"'
-
Admin about 7 years... Or even a little custom script
-
Admin over 2 yearsRegarding the contents of your alias, there's no reason to use
git mv
instead ofmv
because git will detect moves based on content. Rather move and commit, without changing the file, and AFTER commit modify the file. That way git will know that the file is moved. -
Admin over 2 years@Highmastdon true, but the alias has the advantage of making the task faster, easier and cleaner. faster: not having to look am I inside or outside the repo, use only 1 command in git. easier: only the simple mv command everywhere, always. cleaner: no unwanted commit messages floating around in the git history that have to get cleaned out before committing to the company git that has strict rules on commit messages and kind of work that is allowed to have a separate commit. your solution would add commands even if you dont clean up the commits afterwards.
-
-
jhscheer about 7 years"There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell function should be used." gnu.org/software/bash/manual/html_node/Aliases.html#Aliases
-
switch87 about 7 yearsindeed, like Sato Katsura also recomanded me I already did it that way. I will edit your answer with my solution (almost the same but with alias)
-
jhscheer about 7 years@switch87: I'm glad you found a suitable solution for you. It seems your edit got rejected due to a conflict with another (random) edit. I'll add your alias.
-
switch87 over 5 yearsThank you for explaining why my first try did not work.