- How to access Windows folders from Bash on Ubuntu on Windows
- 2 Answers 2
- How to change default directory in Bash for Windows 10? [closed]
- 3 Answers 3
- Set a directory by default on BASH windows [closed]
- 3 Answers 3
- Adding a Bash Console Here command to the context menu of folders in File Explorer
- Bash on Windows: практические опыты по скрещиванию ежей и ужей
- Кейс номер один
- Путь первый — обращение к WMIC
- Путь второй — использование Scripting.FileSystemObject
- Кейс номер два
- Резюме
- How can I set the current working directory to the directory of the script in Bash?
- 11 Answers 11
- For all UNIX/OSX/Linux
How to access Windows folders from Bash on Ubuntu on Windows
On the Bash on Ubuntu on Windows app, I only have
How do I access all of the Windows folders like Documents, Downloads, etc.?
2 Answers 2
You’ll find the Windows C:\ structure at /mnt/c/ in the Bash environment.
Therefore, my Documents folder is at /mnt/c/Users/Ben/Documents/ .
directory, your home in the Bash environment, which is not the root ( / ). If you had done cd / first, you would have seen mnt . – Ben N Apr 16 ’16 at 18:01
Alternatively,
- Hold down Shift while right-clicking in your desired Windows directory
- Select «Open PowerShell window here«
- Once you’re in PowerShell, type bash
You’ll be able to use any Bash commands directly to operate on the files and folders in that Windows directory. By using this method, you don’t have to manually cd into your directories especially when you’ve a deep-rooted directory to access.
Update as of Windows 10 1809:
Above still works, but there’s an easier method now.
- Hold down Shift while right-clicking in your desired Windows directory
- Select «Open Linux shell here«
How to change default directory in Bash for Windows 10? [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 3 years ago .
How can I change the default directory of windows bash to a folder of my choosing?
EDIT: I guess I should have been more clear. When I startup Bash I want it the directory to be in a location of my choosing like Desktop or something. How do I go about setting a default directory?
3 Answers 3
If you want change the directory your bash prompt is starting in, you can edit your .bashrc file. At the bottom, add:
This will go into your home directory. (you can actually do just cd , but I it’s clearer to add the
To edit, you can use vim . If you don’t know how to use it, you can always use nano for the time being, but you really should have a look at it, it’s really powerful.
This will open nano in «full console». At the bottom, you have the few commands you can use ( ^ means control ) Do your changes, hit ctrl+o to save the file (write the file). It’ll ask you where to write, by default, it’s the right location, just hit enter and the .bashrc file will be saved. Then, you can press ctrl+x to exit.
. Do you know how to use vim ? if not, you can use nano: nano
/.bashrc (to exit, press ctrl+o , enter and ctrl+x to save) ( ^ means control ) – math2001 Feb 19 ’17 at 7:11
Steps to set default directory for Bash on Ubuntu on Windows to a folder —
- Open Bash on Ubuntu on Windows.
- cd
to go to home directory of Ubuntu
with your desired location.
- To access your hard disk location make sure you include the mount directory first.
- So if want your Bash to open at C:\dev whenever you open the Bash. You need to replace the cd
with cd /mnt/c/dev at .bashrc file at Ubuntu home directory.
Set a directory by default on BASH windows [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 4 years ago .
The problem I am having is that every time I open bash, it takes me to an unwanted directory, so I have to type the commands cd /mnt/c to get to my PC files like downloads, documents etc. How do I set a directory by default when I open bash?
3 Answers 3
The bash.exe Windows executable that starts Bash on Windows implicitly makes the current directory its startup directory.
That means that you can simply modify the shortcut file that opens Bash and change its Start in: field to open Bash in the directory of choice (specify a regular Windows path; it is automatically translated into a /mnt/c -prefixed path when Bash starts).
- Caveat: The official Bash on Ubuntu on Windows shortcut file (in the Start Menu) passes
as the startup directory as part of the Target: field; simply remove
from the C:\Windows\System32\bash.exe
value in Target: , and then fill in the Start in: field.
Of course, you can create new shortcut files, each with its own startup directory, if desired.
Adding a Bash Console Here command to the context menu of folders in File Explorer
Update: Prerelease build 17666 now comes with a context menu built in — however, it requires you to hold down Shift before right-clicking in order to access it; the solution below may therefore still be of interest if you want the command to show unconditionally.
If you save the following text in a *.reg file and open (double-click) it, you’ll be prompted to import the definitions into your user-specific registry hive.
After import, you’ll find a Bash Console Here command in the context menu of folders in File Explorer, and also when you click in the empty space inside a folder.
On selecting that command, a Bash console window will open in that folder.
Caveat: Because an aux. cmd.exe call must be used to change the directory before invoking bash.exe , the console window will have cmd.exe ‘s icon and will be grouped with regular cmd.exe in the taskbar.
Alternatively, you can use the following PowerShell snippet to create the registry entries:
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» и начать скрещивать ежей и ужей в самых невероятных пропорциях и последовательностях.
How can I set the current working directory to the directory of the script in Bash?
I’m writing a Bash script. I need the current working directory to always be the directory that the script is located in.
The default behavior is that the current working directory in the script is that of the shell from which I run it, but I do not want this behavior.
11 Answers 11
The following also works:
The syntax is thoroughly described in this StackOverflow answer.
Try the following simple one-liners:
For all UNIX/OSX/Linux
Note: A double dash (—) is used in commands to signify the end of command options, so files containing dashes or other special characters won’t break the command.
Note: In Bash, use $
For Linux, Mac and other *BSD:
Note: realpath should be installed in the most popular Linux distribution by default (like Ubuntu), but in some it can be missing, so you have to install it.
Note: If you’re using Bash, use $
Otherwise you could try something like that (it will use the first existing tool):
For Linux specific:
Using GNU readlink on *BSD/Mac:
Note: You need to have coreutils installed (e.g. 1. Install Homebrew, 2. brew install coreutils ).
In bash
In bash you can use Parameter Expansions to achieve that, like:
but it doesn’t work if the script is run from the same directory.
Alternatively you can define the following function in bash:
This function takes 1 argument. If argument has already absolute path, print it as it is, otherwise print $PWD variable + filename argument (without ./ prefix).
or here is the version taken from Debian .bashrc file: