Перейти к содержимому

Профиль MinGW Bash

32

Я использую MinGW в Windows 7. У меня есть .bashrcнесколько псевдонимов. Файл находится в моей домашней папке, куда меня запускает MinGW, поэтому он также считает, что эта папка - моя домашняя папка. Он не загружает содержимое папки автоматически. Я должен запустить bashкоманду, чтобы заставить работать псевдонимы.

Я попытался переименовать его .bash_profile. Это только усугубляло ситуацию, поскольку оно не загружалось автоматически, а также не загружалось при запуске bashвручную.

Как я могу исправить эту проблему?

32 950 просмотров
KurToMe спросил 14 лет назад
K 163

6 ответов

43
Принятый ответ

bashвероятно, начинает работать как оболочка входа в систему, и в этом случае она не читает .bashrcавтоматически. Вместо этого это читает .bash_profile. Из руководства Bash :

Итак, обычно ваш ~ / .bash_profile содержит строку

if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

после (или до) любых инициализаций, специфичных для входа в систему.

Итак, в итоге, создайте .bash_profileфайл в вашем домашнем каталоге и добавьте строку, приведенную выше.

Если ваш вызов bashвызывается как sh, тогда вам нужно использовать .profileвместо него .bash_profile(см. Раздел «Вызов с именем sh» в ссылке на руководство Bash выше).

Спасибо за идею, не сработало. Как я уже говорил в вопросе, размещение команд псевдонимов в .bash_profile не работает вообще, так что кажется, что это не читается.

KurToMe · 14 лет назад · 0

Это дало мне идею сделать именно то, что вы сказали, но вместо этого поместить его в файл .profile. По какой-то причине это сработало (возможно, MinGW не использует Bash по умолчанию или что-то сумасшедшее). Если вы добавите эту опцию в свой ответ, я отмечу ее как принятую.

KurToMe · 14 лет назад · 5

Ах, в моем вопросе была опечатка, которую я исправил, я назвал ее «.bash_rc» в вопросе, но я имел в виду «.bash_profile».

KurToMe · 14 лет назад · 1

несколько более кратко: [-f ~ / .bashrc] &&. ~ / .Bashrc

Rich Homolka · 14 лет назад · 0

@KurToMe Я отредактировал, чтобы осветить твою ситуацию.

jjlin · 14 лет назад · 0
jjlin ответил 14 лет назад
J 11 565
8

Я использую Windows XP, и у меня была такая же проблема. Я нашел HOWTO Создание среды сборки MSYS .

Это важная строка:

Чтобы помочь определить сборку во время выполнения и текущий рабочий каталог, в ~/.profileфайл можно добавить следующее .

В оболочке MinGW я создал .profile:

cd ~ touch .profile 

Я использовал Notepad ++, чтобы отредактировать его как текстовый файл в формате Unix с именем .profileи сохранить его в своем домашнем каталоге,C:\MinGW\msys\1.0\home\Your_Username_Here\.profile

Затем я добавил свой псевдоним и сохранил:

alias n='nano -w' 

Затем я запустил ярлык MinGW Shell из меню «Пуск» и ура, все заработало ! Нано без переноса текста.

Я надеюсь, это поможет вам.

То, что вы говорите, не совпадает ... ~ означает домашний каталог пользователей ... тогда ваше заявление c: \ MinGW \ msys \ 1.0 \ home ... это не имеет никакого смысла, тильда - это ссылка на дом пользователей ... на окнах, которые% userprofile% ...

Eddie B · 13 лет назад · 0

@Bryan: +1 спасибо, это работает

legends2k · 12 лет назад · 2
Bryan ответил 14 лет назад
B 81
2

Я не нашел .bash_profile для меня (он не читался), поэтому я выбрал подход .profile и вставил в него:

exec bash 

Это заменяет мою текущую оболочку новым запуском bash, который читает мой .bashrc

Я думаю, что использование .profile предполагает, что sh используется при входе в систему, а не в bash.

Paul Munsey ответил 11 лет назад
P 21
0

У меня для MINGW, установленного с GIT, работало: .bash_profile положить в C:\Users\[user_name]

Это также каталог, где ~ указывает в оболочке (pwd).

Просто так :)

Koshmaar ответил 11 лет назад
K 59
0

How to set up MSYS Bash initialization files

In the Windows OS, the way you point to the initialization files used by Bash (i.e., profile, bash_profile, bashrc) is different compared to the Linux OS.

The difference between the Windows and Linux OS is their file system structure, which leads to difference in Bash file locations and file naming conventions.

How to set up MSYS Bash initialization files (i.e., profile, bash_profile, and bashrc)

1) In WINOS, open the 'etc' folder located here 'C:\msys\1.0\etc\'. Note. you should see a file 'profile' inside 'etc' folder.

2) Save a no-file-extension file (i.e., when you save set the save as type to '.all files') with the file name '.bash_profile' to 'C:\msys\1.0\home\USERNAME'. Note. there is dot as prefix for the file name (e.g. '.bash_profile') as you would expect in Linux OS Bash setup

2) Save a no-file-extension file (i.e., when you save set the save as type to '.all files') with the file name '.bashrc' to 'C:\msys\1.0\home\USERNAME'. Note. there is dot as prefix for the file name (e.g. '.bash_profile') as you would expect in Linux OS Bash setup

4) Open the 'profile' file in a text editor (sublime text x is good) Note: The file location of 'profile' is 'C:\msys\1.0\etc\'

Inside 'profile' file, scroll to line of text at the end of the file (i.e., scroll to the bottom) you should see a line a test indicating Bash to change its current directory to HOME (In MSYS, HOME is as defined in 'profile' file)

CD $HOME 

5) Before the line with text 'CD $HOME' copy the following code -- adding this script within 'profile' will tell MSYS bash to run the bash_profile #--------------------------------------------------------------------------- #modified BEGIN

# Note. -f is a flag in the file-test operator set of bash commands # that test whether file exists echo '[i] INFO loading personal environment variables and startup programs.... ' BASHRC="$HOME/.bash_profile" if [ -f "$BASHRC" ]; then source "$BASHRC" fi #modified END #--------------------------------------------------------------------------- 

6) Open the 'bash_profile' file in a text editor (Sublime Text x is good) and the end of the file (at bottom of file)

7) Copy the following code at end of file -- adding this script within '.bash_profile' will tell Bash to run the '.bashrc'

#--------------------------------------------------------------------------- #modified BEGIN # Note. -f is a flag in the file-test operator set of bash commands # that test whether file exists BASHRC="$HOME/.bashrc" if [ -f "$BASHRC" ]; then source "$BASHRC" fi #modified END 

#---------------------------------------------------------------------------

8) O.K., now let's write a small script inside '.bashrc' to see if 'profile' is calling 'bash_profile' and if 'bash_profile' is calling '.bashrc'.

8.1) Think of a command name you wish to create. Let's use 't' to mean test

8.2) Open Bash terminal and type 't'. Bash should reply 't: command not found' -- if it does not say 't: command not found' then repeat 8.1 and 8.2 until your command name says 'command not found'. You do not want to alias a command name that is assigned to bash BAD!, so it must be 'command not found'

8.3) O.K., 't' gave me a 't: command not found'. Now let's write the script into '.bashrc'

8.4) In '.bashrc' write

# Use double quotes or bash will not write it alias t="echo passed test" 

8.5) Save file '.bashrc' in 'C:\msys\1.0\home\USERNAME'

9) Almost there. Now restart the Bash terminal, and make sure to close any previously opened Bash terminals

10) Type in terminal 't'. It should reply 'passed test'. If not, carefully check that code was correctly written (start by checking quotes)

Some notes 1) 'source filename' is the same as '. filename'

2) " " double quotes allow variables to be replaced by its contents single quotes do not

3) $HOME is /home/USERNAME same as ~ is /home/USERNAME

4) A function are always preferred over alias 2

For more detail see BASH reference

I am new to Bash. So there is no guarantee I did this the best way.

Good luck!

Atom ответил 10 лет назад
A 11
0

По линии @Koshmarr, но немного по-другому. Мой mingw64, скачанный с git-scm.com, будет загружаться /c/Users/[user-name]при запуске. Все же мой домашний двигатель (найденный cd ~) был в /h/. Я положил .bashrcи .bash_profileв мой ~диск, и все работало.

В .bash_profile:

 source ~/.bashrc; 

Просто выясните, где MINGW считает дом и поместите .bash_profileтуда.

Bryan ответил 9 лет назад
B 131