bashshellgit-bash

(git) Bash: clone and checkout a specific env


I'm trying to do the following with a single git bash script:

  1. cloning a git repo
  2. going into the subfolder where the repo has been cloned
  3. switch to another branch (env/dev)
  4. do a git pull for good measure
  5. go back to the previous folder

I plan to call it as ./clone.sh https://myserver.com/foo/blabla.git

I currently have:

git clone $1 && basename $1 .git|xargs cd && git checkout env/svil && git pull && cd ..

this though gives an error: xargs: cd: No such file or directory after the repo has been cloned. Where am I going wrong and how can I solve this?

please do mind that I don't have a full bash at my disposal, only git bash

Thanks


Solution

  • In order to change the current working directory to <repo_dir>/.git so as to execute your git commands, cd must be a shell built-in; this cannot be an executable you will find on your disk.

    This is because changes made by an executable to its environment (current working dir, environment variables, limits, etc.) have no effect on the calling process (your shell). Thus, even if you had an external cd, like with any command found on your disk, your directory change would be immediately cancelled when your cd command exits, which would defeat its purpose.

    You should instead write:

    git clone "$1" \
    && cd "$(basename "$1" .git)" \
    && git checkout env/svil \
    && git pull \
    && cd ..
    

    Notes: