Home > Software engineering >  alias for a bash cmd with xargs for directories fails
alias for a bash cmd with xargs for directories fails

Time:08-13

I use a command to collect all my projects by searching for a common file (Jenkinsfile) because I want to execute a command in every project directory:

find . -name 'Jenkinsfile' | sed s/Jenkinsfile// |  xargs -L 1 bash -c '(cd $0 && git branch)'

To shorten this for future usage I tried to create an alias for it like this:

alias fgb="find . -name 'Jenkinsfile' | sed s/Jenkinsfile// |  xargs -L 1 bash -c 'cd $0 && git branch'"

But now I only get such error msgs:

./shared/authorization-provider/: line 0: cd: /usr/bin/bash: No such file or directory

What is wrong?

EDIT:

I found a solution:

alias fgb="find . -name 'Jenkinsfile' | sed s/Jenkinsfile// |  xargs -I {} bash -c 'cd {} && pwd && git branch' "

CodePudding user response:

As suggested by Kamil you should try to use functions instead of the more or less obsolete aliases. And find is enough for what you want:

fgb() {
  find . -name 'Jenkinsfile' -execdir 'git branch' \;
}

-execdir runs its command argument from the directory in which a matching file was found.

CodePudding user response:

What is wrong?

$0 is inside " quotes, so it is expanded to /usr/bin/bash. cd $0 -> cd /usr/bin/bash -> no such file or dir.

The millennium long advice is: use a function, not an alias. Instead of an alias, write a function.

fgb() {
   find . -name 'Jenkinsfile' | sed s/Jenkinsfile// |  xargs -L 1 bash -c 'cd $0 && git branch'
}
  • Related