2

I have a BASH script to go through my Git projects recursively and pull them. We use two branches, master and development. When I change the script to include && git checkout development, my script fails to run and I get this error:

find: missing argument to `-exec'

When I remove the && git checkout development part again, the error remains the same even though the script is reverted to its initial state.

Here is the script:

#!/bin/bash
find . -type d -name .git -exec sh -c "cd \"{}\"/../ && pwd && git pull && git status" \;

And here it is with the Git checkout call (and removing git status):

#!/bin/bash
find . -type d -name .git -exec sh -c "cd \"{}\"/../ && pwd && git checkout development && git pull" \;

What is going on here? Is it possibly a red herring that the issue only occurs after changing the script?

3
  • Try this: find . -type d -name .git -exec sh -c 'cd "$1"/../ && pwd && git checkout develop && git pull' _ '{}' \; Commented Aug 17, 2017 at 8:34
  • 1
    That's worked. Thanks! Could you explain why the change makes it work in an answer please? Is the "$1" part of it pulling in a command line argument, or doing something different? Commented Aug 17, 2017 at 8:39
  • No need to use cd: find . -type d -name .git -exec sh -c 'readlink -f "$1"/../ && git -C "$1"/../ checkout develop && git -C "$1"/../ pull' _ '{}' \; Commented Aug 25, 2017 at 11:07

1 Answer 1

2

Don't use placeholder {} inside command string after sh -c. You can use this find:

find . -type d -name .git -exec sh -c \
'cd "$1"/../ && pwd && git checkout develop && git pull' _ '{}' \;

Here we are passing dummy _ to populate $0 in command line and {} is being passed to populate $1 positional argument.

Edit based on comment: After tinkering to pass in arguments to the script, I've found it's easiest to export them for the subshell first:

#!/bin/bash
BRANCH=$2
export BRANCH
echo "Checking out branch $BRANCH"
find . -type d -name .git -exec sh -c 'cd "$1"/../ && pwd && git checkout "$BRANCH" && git pull; echo "Branch being checked out: $BRANCH"' _ '{}' "$BRANCH" \;
Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks. So if I want to pass in a command line argument to tell it which branch to check out, will the "$1" interfere, or have to be changed in any way?
You can pass additional parameters e.g.: -exec sh -c 'cd "$1"/../ && pwd && git checkout develop && git pull; echo "second value: $2"' _ '{}' "value" \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.