directory name and cd of all subdirectories in directory using shell

0

Purpose

For each subdirectory in directory that contains a setup.py, run pip uninstall -y <directory name> and pip install .

Windows solution

> for /D %f in (.\*) do (cd "%cd%\%f" && set s=%f && set j=%s:~3% && pip uninstall %j% && pip install .)

EDIT: Looks like pip uninstall/reinstall can be done with:

(for %F in ("%cd%") do pip uninstall -y "%~nxF") & pip install .

Linux solution

#!/usr/bin/env bash

DIR="${DIR:-$PWD}
VENV="${VENV:-.venv}"
REQUIREMENTS="${REQUIREMENTS:-'requirements.txt'}";

if [ ! -d "$VENV/bin" ]; then
    echo Cannot find "$VENV/bin"
    exit 2;
fi

source "$VENV/bin/activate"

for f in "${DIR[@]}"; do
    if [ -f "$f/setup.py" ]; then
        builtin cd "$f";
        pip uninstall -y "${PWD##*/}";
        if [ -f "$REQUIREMENTS" ]; then
            pip install -r "$REQUIREMENTS"
        fi
        pip install .;
        builtin cd ..;
    fi;
done

As you can see, my Linux solution is much more versatile. Actually my Windows solution doesn't work.

The Windows solution is squashing the strings so things aren't deterministic between runs. Seems to be some weird parameter expansion going on. How am I meant to do it in CMD?

A T

Posted 2017-02-26T12:52:42.660

Reputation: 641

Are you open to Powershell? Have a play around with: get-childitem -ErrorAction SilentlyContinue -recurse "C:\folder\" -filter setup.py | foreach {write-host "pip uninstall -y " $_.directory.fullname; "pip install ."} as a starting point if you are? – HelpingHand – 2017-02-26T13:10:40.237

"The Windows solution is squashing the strings so things aren't deterministic between runs" Please explain what you mean by this. – DavidPostill – 2017-02-26T13:35:14.640

Answers

0

That looks like an unfair comparison between a badly written batch one liner and a full fledged bash script (I agree that cmd.exe is much more limited).
Why do you strip off the first 3 chars from the folder name when uninstalling?

This batch might work:

@Echo off
for /D %%f in (*) do (
  If exist "%f\setup.py" (
    PushD "%%f"
    pip uninstall "%%f"
    pip install .
    PopD
  )
)

LotPings

Posted 2017-02-26T12:52:42.660

Reputation: 6 150

I strip because I get the ./; and it is an unfair advantage because the Windows one is very much a WiP. - Thanks, I'll give yours a shot. – A T – 2017-02-26T13:49:10.263

1Since for /d works from the current path, there is no need to use .\* and with only * there is nothing prepended to the folder name. Converting from a one line I also missed to double the percent signs. Changed above. – LotPings – 2017-02-26T13:54:36.863

Thanks: I'll give that a shot. BTW: The PushD/PopD; is doing the cd right? – A T – 2017-02-28T07:08:42.077

1Yes, pusd put's the current location on a stack and changes to the new folder. Popd returns to the previous folder. – LotPings – 2017-02-28T12:04:06.760