- Bash script to convert windows path to linux path
- 4 Answers 4
- Explanation
- How to add git to PATH (Bash on Windows)
- 2 Answers 2
- Git Bash doesn’t see my PATH
- 20 Answers 20
- Bash on Windows: практические опыты по скрещиванию ежей и ужей
- Кейс номер один
- Путь первый — обращение к WMIC
- Путь второй — использование Scripting.FileSystemObject
- Кейс номер два
- Резюме
- Is there a way to run Bash scripts on Windows? [closed]
- 8 Answers 8
Bash script to convert windows path to linux path
I’m new to shell scripting and trying to accomplish following, converting a windows path to a linux path and navigating to that location:
Input: cdwin «J:\abc\def» Action: cd /usr/abc/def/
So, I’m changing the following:
This is my try, but it doesn’t work. It just returns a blank if i echo it:
4 Answers 4
You need to catch the variable and then process it.
For example this would make it:
And then you call it with
Explanation
is equivalent to
and replaces every \ with / , saving the result into the var line . Note it uses another delimiter, # , to make it more readable. It also removes the leading J: .
/work/projects: No such file or directory , but if I manually run cd
/work/projects from the command line, it works. Any idea what I’m doing wrong? – Josh Oct 30 ’19 at 22:58
sed allows alternative delimiters so better to not to use / .
Try this sed command:
You don’t even need to use sed (although there’s nothing wrong with using sed). This works for me using bash string substitution:
Substitution works as follows (simplification):
and double slash means replace all:
In argument 1 , replace the first instance of J: with /usr :
In variable line replace all ( // ) backslashes (escaped, \\ ) with ( / ) forwardslash ( / ):
echo the output of any of those to see how they work
How to add git to PATH (Bash on Windows)
I am using Bash on Ubuntu on Windows, and I installed git. How do I add git to my PATH?
2 Answers 2
The General command is (using setx ):
On WSL (Windows Subsytem for Linux), you would type, after installation:
It should be already in your PATH ( /usr/bin or /usr/local/bin )
If it is not, you can try and find it: find / -name «git» , and add it to your
But be aware the WSL will install an old version of Git.
Fir the most recent one, use:
Under C:\Users\**user**\AppData\Local\lxss , You will find:
- root folder
- home folder
- and a hidden rootfs folder ( \bin , \boot , \dev , \etc. )
DON’T CHANGE ANYTHINK INSIDE! SERIOUSLY! 🚨
Access Windows files via /mnt/**letter**/
Maybe I don’t fully understand what Bash on Ubuntu on Windows is.
Windows Subsystem for Linux (WSL) is a compatibility layer for running Linux binary executables (in ELF format) natively on Windows 10.
Windows Subsystem for Linux is only available on 64-bit editions of Windows 105 and can be activated on Windows 10 Anniversary Update and later.
WSL uses fewer resources than a full virtualized machine, the most direct way to run Linux software on a Windows computer, while also allowing users to use Windows apps and Linux tools on the same set of files.5
So if I install git and it’s in /usr/bin/git , does that correspond to a particular folder such as C:\Program Files\etc. ?
Yes, under C:\Users\**user**\AppData\Local\lxss\rootfs\usr\. , but you are not supposed to access it directly. You only use it through the WSL bash.
Is setting my PATH different by putting it in my
/.profile vs. going into Control Panel —> System Properties —> Environment Variables
Yes, completely. If you want to set your Windows Environment Variables PATH, you need to use Git for Windows, as described in here.
Git Bash doesn’t see my PATH
When I use Git Bash (on Windows), I cannot run any executable without specifying its full path, although it is located in a folder which is in my PATH variable. Looks like bash doesn’t recognize it. Why? Can I fix it?
20 Answers 20
Got it. As a Windows user, I’m used to type executable names without extensions. In my case, I wanted to execute a file called cup.bat . In a Windows shell, typing cup would be enough. Bash doesn’t work this way, it wants the full name. Typing cup.bat solved the problem. (I wasn’t able to run the file though, since apparently bash couldn’t understand its contents)
One more reason to switch to posh-git..
Thanks @Tom for pointing me to the right direction.
Maybe bash doesn’t see your Windows path. Type env|grep PATH in bash to confirm what path it sees.
/.bashrc» in git bash/cygwin), then add «PATH=$PATH: : . » to this file. So, if you wanted «/usr/bin/mypath» to be in the PATH variable, this line would read: PATH=$PATH:/usr/bin/mypath – Daniel May 27 ’14 at 20:25
Following @Daniel’s comment and thanks to @Tom’s answer, I found out that Git bash was indeed using the PATH but not the latest paths I recently installed. To work around this problem, I added a file in my home (windows) directory named:
and the content as follow:
because I was installing Go and this path contained the executable go.exe Now Git bash was able to recognize the command:
Perhaps just a system reboot would have been enough in my case, but I’m happy that this solution work in any case.
Create a file in C:\Users\USERNAME which is called config.bashrc, containing:
Now move the file on the command line to the correct location:
While you are installing Git, you can select the option shown below, it’ll help you to set the path automatically.
Its worked out for me 🙂
Restart the computer after has added new value to PATH.
Old question but it can help someone else.
I’ve changed my PATH user wide, after that I’ve just logoff and login again.
That is it! git bash loaded the new PATH value correctly.
I can confirm that restarting the system will make sure that the PATH set in the environment variable in windows is picked up by git and there is no other automatic way.
In case your git-bash ‘s PATH presents but not latest and you don’t want a reboot but regenerate your PATH s, you can try the following:
Bash on Windows: практические опыты по скрещиванию ежей и ужей
В прилетевшем обновлении Windows 10 Creators Update появилась интереснейшая возможность — запускать виндовые программы в этом их линуксе. Официальные примеры меня категорически не устроили — евангелисты Microsoft предложили мне рисовать корову в PowerShell и запускать Notepad из bash. Чё, правда? Это всё до чего вы додумались?
Как человек страстно ждавший возможность запуска exe-файлов внутри WSL, я хочу поделиться опытом правильного использования новой фичи.
Bash on Windows я использую для всякой мелкой механизации — выкачать, распарсить, проанализировать. Взять 10-20 гигов логов и поколдовать над ними в поисках чего нибудь этакого. Взять 200 гигов исходных данных, сделать ВЖУХ и пульнуть пару мегов результатов в базу сайта. Вобщем, обычная бытовуха, как у всех. Разве нет?
Кейс номер один
Вот то ради чего именно я ждал возможность запуска exe-файлов на WSL.
Имеется некоторое количество веб-сайтов для разных программ, требуется проверить что все ссылки «download» ведут на актуальные версии.
Пропустив этап поиска ссылок и скачивания файлов перейдём к извлечению нужной информации.
Делаем это двумя путями.
Путь первый — обращение к WMIC
В CMD вызов данной информации выглядит вот так:
/VALUE — что бы получить всю возможную информацию
В bash это выглядит вот так
слэшей много и все нужные
Но мне то нужно не просто на экран вывести, а получить и обработать.
Поэтому, в PHP это выглядит вот так:
/mnt/c/Windows/System32/cmd.exe — полный путь, что бы наверняка
$b — результат многострочный, поэтому получаем его в виде массива (в $a попадает лишь последняя строчка)
$ini — формат результата совместим с ini-файлом, грех этим не воспользоваться — превращаем полученный массив $b в текст для последующего преобразования с помощью parse_ini_string().
Путь второй — использование Scripting.FileSystemObject
Данной решение я нашёл здесь и немножко допилил.
В исходном варианте был вызов короткого списка с результатами, что меня не устроило
Я заменил эту строчку на цикл извлекающий ВСЕ возможные свойства файла
формат вывода сделан совместимым с ini-файлом.
PHP код, вызывающий bat-файл, получился вот такой
Почти так же как как в случае с WMI, только приходится перекодировать результат в юникод. ( CP866 — всплакнул )
Склеиваем полученные результаты в единый текст и парсим
Делаем разбиение на секции (второй параметр — true) и во избежании проблем включаем — INI_SCANNER_RAW
ВЖУХ и получаем массив всех возможных свойств файла с которым удобно работать.
Array
(
[WMIC] => Array
(
[AccessMask] => 1179817
[Archive] => TRUE
[Caption] => c:\windows\system32\cmd.exe
[Compressed] => FALSE
[CompressionMethod] =>
[CreationClassName] => CIM_LogicalFile
[CreationDate] => 20170318235750.921718+180
[CSCreationClassName] => Win32_ComputerSystem
[CSName] =>
[Description] => c:\windows\system32\cmd.exe
[Drive] => c:
[EightDotThreeFileName] => c:\windows\system32\cmd.exe
[Encrypted] => FALSE
[EncryptionMethod] =>
[Extension] => exe
[FileName] => cmd
[FileSize] => 271872
[FileType] => Application
[FSCreationClassName] => Win32_FileSystem
[FSName] => NTFS
[Hidden] => FALSE
[InstallDate] => 20170318235750.921718+180
[InUseCount] =>
[LastAccessed] => 20170318235750.921718+180
[LastModified] => 20170318235750.921718+180
[Manufacturer] => Microsoft Corporation
[Name] => c:\windows\system32\cmd.exe
[Path] => \windows\system32\
[Readable] => TRUE
[Status] => OK
[System] => FALSE
[Version] => 10.0.15063.0
[Writeable] => TRUE
)
[FileSystemObject] => Array
(
[Имя] => cmd.exe
[Размер] => 265 КБ
[Тип элемента] => Приложение
[Дата изменения] => 18.03.2017 23:57
[Дата создания] => 18.03.2017 23:57
[Дата доступа] => 18.03.2017 23:57
[Атрибуты] => A
[Автономность] =>
[Доступность] => Доступен автономно
[Распознанный тип] => Приложение
[Владелец] => TrustedInstaller
[Вид] => Программа
[Дата съемки] =>
[Исполнители] =>
[Альбом] =>
[Год] =>
[Жанр] =>
[Дирижер] =>
[Теги] =>
[Оценка] => Без оценки
[Авторы] =>
[Название] =>
[Тема] =>
[Категории] =>
[Комментарии] =>
[Авторские права] => c Microsoft Corporation. All rights reserved.
[№] =>
[Продолжительность] =>
[Скорость потока] =>
[С защитой] =>
[Камера, модель] =>
[Размеры] =>
[Камера, изготовитель] =>
[Организация] => Microsoft Corporation
[Описание файла] => Windows Command Processor
[Ключевые слова образцов] =>
[Имя программы] =>
[Длительность] =>
[В сети] =>
[Повторяется] =>
[Место] =>
[Адреса необязательных участников] =>
[Необязательные участники] =>
[Адрес организатора] =>
[Имя организатора] =>
[Время оповещения] =>
[Адреса обязательных участников] =>
[Обязательные участники] =>
[Ресурсы] =>
[Состояние собрания] =>
[Свободно/Занято] =>
[Общий размер] => 227 ГБ
[Учетная запись] =>
)
)
К чему был весь этот стрёмнокод? А вот к чему.
Как я уже упомянул ранее, на сайте майкрософта поведали, что теперь мы можем рисовать коров в PowerShell и запускать notepad.exe из баша.
А в обсуждении перевода этого майкрософтовского текста люди выясняют насколько там честный линукс и можно ли на него взгромоздить Докера.
Люди, вы не туда смотрите! Я в bash выполнил PHP-скрипт который через exec() запустил bat-файл в котором JScript создал ActiveXObject.
It’s Kind Of Magic!
А ещё я могу из CMD сделать вот так:
Кейс номер два
Обновление Windows 10 Creators Update я накатил 6 числа, а на прошлой недели был отвлечён от новой игрушки бухгалтерией. Бухгалтерия запросила оригиналы первички.
Эврика, подумал я и поставил консольную печаталку
Лезем в bash и просто запускаем программу
Результат — из принтера ползут листочки:
(данный скриншот — последующая имитация на виртуальном принтере, но на реальном HP тоже сработало)
В результате имеем:
- программа проявила интерактивность (триалка запросила нажать кнопочку)
- из башевского окошка полезла по своим виндовым путям
- взяла оттуда файлы с русскими названиями
- вызвала офисный редактор через COM-объекты
- отправила результат на принтер
То есть можно не только писать простейшие скриптики, но и использовать сложные программы.
Резюме
Я ещё не до конца осознал что ещё с этим можно делать, но эта штука может гораздо больше чем просто беседа с коровами и запуск LAMP.
Надо просто самому себе разрешить вырваться из дихотомиии «либо Linux, либо Windows» и начать скрещивать ежей и ужей в самых невероятных пропорциях и последовательностях.
Is there a way to run Bash scripts on Windows? [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 5 years ago .
I have bought and I use Windows 7 Ultimate, and I like to use it to develop applications. One of the down sides (as with every OS) is that I can not run Bash scripts. Is there a way to run Bash scripts on Windows by installing some software? It is ok if it does not work 100%, but as long as the most common functionality is available it should be great.
8 Answers 8
Install Cygwin, which includes Bash among many other GNU and Unix utilities (without whom its unlikely that bash will be very useful anyway).
Another option is MinGW’s MSYS which includes bash and a smaller set of the more important utilities such as awk. Personally I would have preferred Cygwin because it includes such heavy lifting tools as Perl and Python which I find I cannot live without, while MSYS skimps on these and assumes you are going to install them yourself.
Updated: If anyone is interested in this answer and is running MS-Windows 10, please note that MS-Windows 10 has a «Windows Subsystem For Linux» feature which — once enabled — allows you to install a user-mode image of Ubuntu and then run Bash on that. This provides 100% compatibility with Ubuntu for debugging and running Bash scripts, but this setup is completely standalone from Windows and you cannot use Bash scripts to interact with Windows features (such as processes and APIs) except for limited access to files through the DrvFS feature.
Best Option I could find is Git Windows Just install it and then right click on and click «Git Bash Here» this will open a bash window
This will open a bash window like this:
and the linux commands work.
I’ve tried ‘sh’ , ‘vi’ , ‘ssh’ , ‘curl’ ,etc. commands
If your looking for something a little more native, you can use getGnuWin32 to install all of the unix command line tools that have been ported. That plus winBash gives you most of a working unix environment. Add console2 for a better terminal emulator and you almost can’t tell your on windows!
Cygwin is a better toolkit overall, but I have found myself running into suprise problems because of the divide between it and windows. None of these solutions are as good as a native linux system though.
You may want to look into using virtualbox to create a linux VM with your distro of choice. Set it up to share a folder with the host os, and you can use a true linux development environment, and share with windows. Just watch out for those EOL markers, they get ya every time.
Best option? Windows 10. Native Bash support!
You can always install Cygwin to run a Unix shell under Windows. I used Cygwin extensively with Window XP.
After installing git-extentions (http://gitextensions.github.io/) you can run .sh file from the command prompt. (No ./script.sh required, just run it like a bat/cmd file) Or you can run them in a «full» bash environment by using the MinGW Git bash shell.
I am not a great fan of Cygwin (yes I am sure it’s really powerful), so running bash scripts on windows without having to install it perfect for me.
In order to run natively, you will likely need to use Cygwin (which I cannot live without when using Windows). So right off the bat, +1 for Cygwin. Anything else would be uncivilized.
HOWEVER, that being said, I have recently begun using a combination of utilities to easily PORT Bash scripts to Windows so that my anti-Linux coworkers can easily run complex tasks that are better handled by GNU utilities.
I can usually port a Bash script to Batch in a very short time by opening the original script in one pane and writing a Batch file in the other pane. The tools that I use are as follows:
I prefer UnxUtils to GnuWin32 because of the fact that [someone please correct me if I’m wrong] GnuWin utils normally have to be installed, whereas UnxUtils are standalone binaries that just work out-of-the-box.
However, the CoreUtils do not include some familiar *NIX utilities such as cURL, which is also available for Windows (curl.haxx.se/download.html).
I create a folder for the projects, and always SET PATH=. in the .bat file so that no other commands other than the basic CMD shell commands are referenced (as well as the particular UnxUtils required in the project folder for the Batch script to function as expected).
Then I copy the needed CoreUtils .exe files into the project folder and reference them in the .bat file such as «.\curl.exe -s google.com», etc.
The Bat2Exe program is where the magic happens. Once your Batch file is complete and has been tested successfully, launch Bat2Exe.exe, and specify the path to the project folder. Bat2Exe will then create a Windows binary containing all of the files in that specific folder, and will use the first .bat that it comes across to use as the main executable. You can even include a .ico file to use as the icon for the final .exe file that is generated.
I have tried a few of these type of programs, and many of the generated binaries get flagged as malware, but the Bat2Exe version that I referenced works perfectly and the generated .exe files scan completely clean.
The resulting executable can be run interactively by double-clicking, or run from the command line with parameters, etc., just like a regular Batch file, except you will be able to utilize the functionality of many of the tools that you will normally use in Bash.
I realize this is getting quite long, but if I may digress a bit, I have also written a Batch script that I call PortaBashy that my coworkers can launch from a network share that contains a portable Cygwin installation. It then sets the %PATH% variable to the normal *NIX format (/usr/bin:/usr/sbin:/bin:/sbin), etc. and can either launch into the Bash shell itself or launch the more-powerful and pretty MinTTY terminal emulator.
There are always numerous ways to accomplish what you are trying to set out to do; it’s just a matter of combining the right tools for the job, and many times it boils down to personal preference.