Как добавить команду «дерево» в git-bash в Windows?

29587
jcollum

Я использую git-bash в Windows 7. Я хотел бы увидеть дерево текущего каталога. Тем не мение:

jcollum@DEVELOPER01 ~/Dev/express_coffee  $ tree .  sh.exe": tree: command not found 

ОК, поэтому у меня нет команды дерева. Как мне это установить? Я нашел статью, но она была для Mac.

41
`git-bash` на самом деле просто урезанная версия Cygwin. Лучший способ - установить Cygwin с сайта cygwin.com и использовать менеджер пакетов для установки `дерева` или любого пакета, в котором он находится (если он существует). Horn OK Please 11 лет назад 0
@allquixotic на самом деле в эти дни это Mingw jcollum 11 лет назад 2

8 ответов на вопрос

30
Viktor Mellgren

You could also use "cmd //c tree" to use Windows' tree

Explanation:

  • Launch cmd with '/c' argument and run tree, then terminate

/C Carries out the command specified by string and then terminates

(extra slash for escaping)

Answered in greater detail here: https://stackoverflow.com/q/515309/1261166

18
Pini Cheyni

Я скачал tree.exe внутри zip-файла отсюда http://gnuwin32.sourceforge.net/packages/tree.htm, как было предложено.

Затем я извлек файл tree.exe в C:\Program Files\Git\usr\bin(я добавил эту папку в путь Windows, чтобы он работал с обычным CMD, но он также работает и с GITBash). Git Bash with tree command on windows

Я надеюсь, что это поможет вам как-то!

Работает очень хорошо с git-bash на Windows 7, спасибо! cjauvin 7 лет назад 2
Tree.exe, скопированный в C: \ Program Files \ Git \ usr \ bin, - это то, что мы искали. Отличная доля. Благодарю. http://downloads.sourceforge.net/gnuwin32/tree-1.5.2.2-bin.zip Загрузите zip-файл, указанный для двоичных файлов, в которых есть tree.exe. Наоборот попробуйте скачать с оригинального сайта. Doogle 6 лет назад 2
В Windows 10 я помещаю это в `C: \ Users \ myuser \ AppData \ Local \ Programs \ Git \ usr \ bin`. Я думаю, что эмпирическое правило заключается в том, чтобы найти, где находятся bash.exe или git.exe. папку, затем найдите usr / bin / и поместите туда дерево Charles L. 5 лет назад 0
7
Brian Burns

Сборка дерева GnuWin32 находится по адресу http://gnuwin32.sourceforge.net/packages/tree.htm - вам нужно добавить его в свой путь вручную, если вы еще не используете GnuWin32.

Если вы хотите использовать его на консоли Windows, вам также нужно переименовать или скопировать tree.exe во что-то другое, например, lstree.exe, в противном случае команда дерева Windows будет иметь приоритет. Преимущество версии GnuWin состоит в том, что она имеет много опций - например tree -L 2, ограничит глубину рекурсии до 2.

> tree --help usage: tree [-adfghilnpqrstuvxACDFNS] [-H baseHREF] [-T title ] [-L level [-R]] [-P pattern] [-I pattern] [-o filename] [--version] [--help] [--inodes] [--device] [--noreport] [--nolinks] [--dirsfirst] [--charset charset] [--filelimit #] [<directory list>] -a All files are listed. -d List directories only. -l Follow symbolic links like directories. -f Print the full path prefix for each file. -i Don't print indentation lines. -q Print non-printable characters as '?'. -N Print non-printable characters as is. -p Print the protections for each file. -u Displays file owner or UID number. -g Displays file group owner or GID number. -s Print the size in bytes of each file. -h Print the size in a more human readable way. -D Print the date of last modification. -F Appends '/', '=', '*', or '|' as per ls -F. -v Sort files alphanumerically by version. -r Sort files in reverse alphanumeric order. -t Sort files by last modification time. -x Stay on current filesystem only. -L level Descend only level directories deep. -A Print ANSI lines graphic indentation lines. -S Print with ASCII graphics indentation lines. -n Turn colorization off always (-C overrides). -C Turn colorization on always. -P pattern List only those files that match the pattern given. -I pattern Do not list files that match the given pattern. -H baseHREF Prints out HTML format with baseHREF as top directory. -T string Replace the default HTML title and H1 header with string. -R Rerun tree when max dir level reached. -o file Output to file instead of stdout. --inodes Print inode number of each file. --device Print device ID number to which each file belongs. --noreport Turn off file/directory count at end of tree listing. --nolinks Turn off hyperlinks in HTML output. --dirsfirst List directories before files. --charset X Use charset X for HTML and indentation line output. --filelimit # Do not descend dirs with more than # files in them. 

По сравнению с деревом Windows:

> tree /? Graphically displays the folder structure of a drive or path.  TREE [drive:][path] [/F] [/A]  /F Display the names of the files in each folder. /A Use ASCII instead of extended characters. 
IMO, это самый простой способ получить дерево CMD в Cygwin, и я пробовал маршрут компиляции, прежде чем безуспешно. При этом вы просто скачиваете бинарный файл, распаковываете его в папку на вашем пути к cygwins и ViLA, дерево команды из коробки iloveretards 8 лет назад 0
в cygwin: `apt-cyg install tree` и` tree.exe` будут находиться в папке cygwin `bin`. Timo 6 лет назад 0
6
blur

В Windows уже есть команда дерева - единственная проблема - это tree.com, и git bash не будет автоматически добавлять расширение .com и выполнять его.

Однако он найдет его, если вы нажмете клавишу Tab после того, как наберете дерево или тре

Чтобы увидеть файлы, которые вы должны использовать // f - вы должны использовать // или bash подумает, что это имя папки

Я также использовал // a, чтобы показать строки ascii, но вам не нужно его использовать

Пример:

dean@dean:~/java$ tree bash: tree: command not found dean@dean:~/java$ tree.com //a Folder PATH listing for volume c Volume serial number is 4E70-B37A C:. +---atom +---sublime \---vscode dean@dean:~/java$ tree.com //a //f Folder PATH listing for volume c Volume serial number is 4E70-B37A C:. +---atom | test1 | +---sublime | test2 | \---vscode test3  dean@dean:~/java$ 
офигенно, работал как шарм .. Santosh Kumar A 5 лет назад 0
2
Jonathan Hartley

git-bash is really just a cut down version of mingw. Install Cygwin from cygwin.com, and then either use the package manager to install 'tree' or whatever package it's in, or if it doesn't exist, then install gcc, download the tree source from here:

http://mama.indstate.edu/users/ice/tree/

Then follow the instructions in the INSTALL file (make, make install)

Так разве это невозможно в minggw? Jen S. 10 лет назад 0
Я полагаю, что это не так уж сложно из mingw, но это невозможно из стандартного приглашения git-bash, потому что я представляю, что git-bash не поставляется с инструментами, которые вам нужны, как компилятор C / C ++. Но вы можете попробовать установить mingw, обязательно включив gcc, и следуя инструкциям в дереве INSTALL. В прошлом я использовал mingw для компиляции подобных вещей в Windows, так что эта часть определенно возможна. Jonathan Hartley 10 лет назад 1
0
Lucas Amorim Silva

You must install the Three for Windows as said above by the link: http://gnuwin32.sourceforge.net/packages/tree.htm

Besides that you need to add the tree program to your windows path or the tree command will be available only on cmd. Access your windows path and add this (for default installation):

;C:\Program Files (x86)\GnuWin32\bin 

Them you will be able to use tree command on git bash on windows.

0
Delphine

This is the beginning of my .gitconfig file : I made an alias for log --graph

# This is Git's per-user configuration file. [user] # Please adapt and uncomment the following lines: name = xxxxxx email = xxx@xxx.xxx [alias] tree = log --graph --oneline --all --pretty=format:'%C(yellow)%h%Creset -%Cred%d%Creset %s %Cgreen%cr%Creset %C(cyan)%an%Creset %gn' 
Не решение. Псевдоним показывает коммит, а не файлы / каталоги. Timo 6 лет назад 0
0
N. Ngo

Git для Windows ( https://gitforwindows.org/ ) (есть Git Bash), но он не включает tree. treeдоступно через pacman(Диспетчер пакетов), но доступно только в том случае, если вы устанавливаете «Git for Windows SDK » (прокрутите страницу вниз до gitforwindows.org/, где есть ссылка для загрузки установщика для него с https://github.com/ git-for-windows / build-extra / release / latest )

Это ТАК: "Управление пакетами в git для windows?" было очень полезно https://stackoverflow.com/questions/32712133/package-management-in-git-for-windows

Также, как прокомментировано в приведенном выше SO, они ссылаются на эту проблему с git for windows [Pacman отсутствует в новой версии 2.5.2 установки # 397], которую он не должен был включать pacmanв установку по умолчанию.

В любом случае, я установил «Git для Windows SDK», затем в командной строке bash (SDK-64) я запустил следующее для установки текущего дерева v1.7.0-1 (на момент публикации 30 августа 2018 г.):

[SDK-64: Bash Terminal for Git for Windows SDK] pacman -S tree ... Proceed with installation? [Y/n] Y 

В моей системе Git для Windows SDK устанавливается в:, C:\git-sdk-64поэтому из моей оболочки Git для Windows Bash (у которой не было установленного дерева) я скопировал его через tree.exe в каталог / usr / bin, например

[MINGW64: Bash Terminal for Git for Windows] cd /usr/bin cp /c/git-sdk-64/usr/bin/tree.exe . 

Теперь я могу запустить treev1.7.0 из обеих оболочек Git Bash.

Итак, чтобы сделать его еще проще для других и, возможно, для себя на будущей машине, я посмотрел, откуда pacmanвзялся treeпакет, запустив в моем терминале Git для Windows SDK Bash следующее:

$ pacman -S --info tree Repository : msys Name : tree Version : 1.7.0-1 Description : A directory listing program displaying a depth indented list of files Architecture : x86_64 ... 

Ключевым моментом здесь является pacmanполучение его из репозитория «msys» (к вашему сведению: хотя в нем указано «msys», оно действительно использует msys2), поэтому я посмотрел, /etc/pacman.d/mirrorlist.msysи первое зеркало указывает наhttp://repo.msys2.org/msys/$arch/

Поэтому в следующий раз, когда вам понадобится пакет, отсутствующий в Git для Windows, вы можете загрузить его с: http://repo.msys2.org/msys/x86_64/ (для 64-разрядных) или с http: //repo.msys2. .org / msys / i686 / (32-разрядная версия )

Например, прямая ссылка для загрузки дерева v1.7.0-1

К сведению: загрузка окна Git SCM по адресу https://git-scm.com/download/ позволяет получить последние новости из Git для Windows GitHub (https://github.com/git-for-windows/git/releases/) из https: //github.com/git-for-windows/git N. Ngo 5 лет назад 1

Похожие вопросы