Время на прочтение6 мин
Количество просмотров7.9K
Эта статья предназначена для тех, кто уже имеет начальный уровень работы с Git и BitBucket. В статье рассматриваются примеры в Git Bash version 2.33.0, API BitBucket 2.0, https://bitbucket.org
-
Что такое alias (знакомство)
-
Создание alias с выполнением функции
-
Alias с переменной
-
Alias для создания удаленного репозитория BitBucket в Git Bash
1. Что такое alias (знакомство)
В Git имеется возможность добавления собственных команд, которые значительно расширяют возможности Git-а, как инструмента. Вы можете создавать собственные команды и научить Git выполнять их. А также делать существующие длинные команды Git-а более короткими, что значительно сократить время вашей работы с Git-ом. Я не буду описывать все команды, которые можно создавать в Git, а расскажу только самые полезные и интересные.
Итак, начнем!
Самые частые команды, которые мы используем – это:
$ git add .
$ git commit -m "message"
И каждый раз мы вводим их, чтобы добавить в индекс новые или измененные файлы и зафиксировать эти изменения. Но можно существенно сократить время на ввод этих команд, если создать новую команду, которая будет объединять несколько последовательных команд.
Новые команды можно создавать с помощью встроенной команды Git-а: alias.
Давайте создадим нашу первую команду. Введите в Git Bash:
$ git config --global --add alias.ac '!git add -A && git commit -m'
В этом примере мы создали команду ac, которая объединяет команды Git: add . и commit -m.
Знак {!} – оповещает, что будет команда оболочки.
Параметр --global
указывает, что изменения вносятся в глобальный конфигурационный файл Git — а (т.е. корневой каталог, куда установлен Git), а не репозитория.
Параметр --add
, как не сложно догадаться, добавляет новый алиас. Если вы хотите удалить алиас, то следует заменить --add
на --unset
. Если хотите перезаписать алиас, то тогда нужно поставить --replace-all
.
Зайдите в какой-нибудь локальный репозиторий (Git Bash):
$ cd c:/workspace/first_repo
Теперь попробуем выполнить новую команду в Git Bash:
$ git ac
Результат:
[master 04851cd] test new alias ac
1 file changed, 1 insertion(+)
create mode 100644 11.txt
Команда отличная, но я привыкла после этих команд выполнять git status, чтобы посмотреть текущий статус репозитория. Поэтому предлагаю еще расширить возможности новой команды.
Перепишем алиас ac:
$ git config --global --replace-all alias.ac '!git add -A && git commit -m && git status'
Если выполнить команду ac в таком варианта, то git Bash выдаст ошибку:
error: pathspec ‘arg’ did not match any file(s) known to git
Потому что после команды commit -m ожидается комментарий:
$ git commit -m "какой-то комментарий"
И комментарий – это динамический параметр, поэтому здесь нужна переменная, в которую мы будем передавать свое значение. Правильное добавление алиаса будет таким:
$ git config --global --replace-all alias.ac '!git add -A && git commit -m "$1" && git status'
Теперь выполним команду ac в Git Bash:
$ git ac "test arg"
Результат:
[master 7949a4d] test arg
1 file changed, 1 insertion(+), 1 deletion(-)
On branch master
Your branch is ahead of 'origin/master' by 2 commits.
(use "git push" to publish your local commits)
nothing to commit, working tree clean
Все работает верно! Наш комментарий «test arg» передался в переменную $1 и выполнил последовательно команды Git-а.
Ну вот теперь, когда мы познакомились с alias, можно попробовать что-то посложнее.
2. Создание alias с выполнением функции
Создадим функцию с bash-командами и обернем ее командой Git-а. Т.е. при выполнении команды Git-а, выполнится функция с bash командами. Создайте в директории с установленным Git-ом файл ~\Git\etc\.my_functions и пропишите там функцию fn:
fn() {
echo "Hello, world!"
}
Затем откройте git bash и командой добавьте alias, который назовем echofn:
$ git config --global --add alias.echofn $'!bash -c \'source /etc/.my_functions && fn\''
Алиас echofn будет запускать bash, а bash -с, в свою очередь, выполнит строку в одинарных кавычках. В строке команда source прочитает файл .my_functions и выполнит функцию fn. Обратите внимание, что внутренние одинарные кавычки должны быть экранированы (\’), т.к. они находятся внутри одинарных кавычек. Впереди с описанием команды необходимо поставить знак $, чтобы правильно передать всю строку с bash командами и не возникало ошибки: bash: syntax error near unexpected token `}’
Теперь, если выполним нашу новую команду в Git Bash:
$ git echofn
, то получим результат:
Hello, world!
3. Alias с переменной
Есть еще способ создания алиаса. Можно команды-алиасы прописывать прямо в файлах Git-а. Пропишите в файле ~\Git\etc\gitconfig строки:
[alias]
hw = "!f(){ echo \"Hello World!!\"; echo \"My name is $1. And I'm developer\"; };f "
Затем запустите новую команду {hw} в Git Bash:
$ git hw "Olga"
Результат:
Hello World!!
My name is Olga. And I'm developer
Чтобы посмотреть все наши созданные алиасы, выполните команду в Git Bash, чтобы прочитать строки с помощью регулярного выражения, начинающиеся со слова «alias» из конфигурационных настроек Git-а:
$ git config --get-regexp '^alias\.'
А еще лучше создайте новую команду Git-a. Выполните команду в Git Bash:
$ git config --global alias.aliases "config --get-regexp '^alias\.'"
(а затем выполните созданную команду в Git Bash):
$ git aliases
Результат покажет все ваши алиасы:
alias.hw !f(){ echo "Hello World!!"; echo "My name is $1. And I'm developer"; };f
alias.echofn !bash -c 'source /etc/.my_functions && fn'
alias.ac !git add -A && git commit -m "$1" && git status
alias.aliases config --get-regexp '^alias\.'
4. Alias для создания удаленного репозитория BitBucket в Git Bash
Самое полезное я оставила на конец. Если вы используете в качестве удаленного репозитория BitBucket, то наверняка сталкивались с такой проблемой – как создать новый репозиторий из консоли. Например: вы создали новый репозиторий на локальной машине, делали в нем изменения файлов. И вот когда закончили и решили запушить это на BitBucket, то вам выдается ошибка, что на BB репозитория нет и его надо сначала создать. Вы идете на сайт BitBucket-а, создаете там пустой репозиторий, потом из консоли Git Bash делаете связку с удаленным репозиторием. Не слишком изящно, да? Если у вас нет возможности установить дополнительные инструменты, то тут как раз подойдет создание новой команды.
На площадке BitBucket есть API, который позволяет исполнять команды для различных действий. Документацию по API команд вы можете посмотреть тут.
Цепочка команд формируется в виде форматированного контента в формате JSON. А далее необходимо этот форматированный контент послать на ресурс API BitBucket. Послать можно с помощью библиотеки CURL, которая поставляется вместе с пакетом Git Bash.
Пропишите в файле ~\Git\etc\.my_functions строки:
namerep="$1"
new_repo() {
curl -X POST -u "{login_id}:{app_password}" -H "Content-Type: application/json" \
https://api.bitbucket.org/2.0/repositories/iammultic/"$namerep" \
-d '{ "scm": "git", "is_private": true, "project": {"key": "MAIN"}}'
}
Итак, мы создали функцию new_repo, которая будет создавать с помощью Curl и API BitBucket 2.0.
удаленный репозиторий. Вместо {login_id} – вы прописываете свой логин, зарегистрированный в BitBucket; вместо {app_password} – прописываете APP пароль, который можно сгенерировать в BitBucket-е нажав на свой профиль-> Personal settings-> App Paswords-> Create app password. Откроется диалоговое окно:
Затем выбираете необходимые параметры и жмете Create.
Далее вы увидите пароль – строку:
Запишите свой пароль. Этот пароль вы можете использовать для аутентификации в различных приложениях. Например: графических редакторах версионного контроля и т.д.
Вернемся к нашей функции new_repo… Обратите внимание на строку перед функцией namerep= «$1». «$1» – это параметр, который будет передаваться из Git, а namerep – это глобальная bash переменная, которая потом будет использована внутри функции. Эта переменная будет принимать наименование нашего нового репозитория.
Теперь, в файле ~\Git\etc\gitconfig пропишите строки и сохранитесь:
[alias]
cr = "! bash -c 'source /etc/.my_functions && new_repo ' $1"
Далее, выполните новую команду в Git Bash:
$ git cr repo1
Если вы посмотрите в своем аккаунте список репозиторий в BB, то увидите там новый репозиторий repo1
Удаленный репозиторий мы создали, но нам надо также его создать на локальной машине и связать его с удаленным. Здесь можно выбрать — каким способом вы хотите сделать связь между удаленным и локальным репозиторием. Можно сделать клон:
1 вариант
$ cd c:/workplace
$ clone git@bitbucket.org:iammultic/repo1.git
, либо создать такую директорию в вашей рабочей области на локальной машине и связать репозитории:
2 вариант
$ cd c:/workplace
$ mkdir repo1
$ cd c:/workplace/repo1
$ git remote add origin git@bitbucket.org:iammultic/repo1.git
Я выбираю первый вариант.
Добавьте пару строк в ранее созданную функцию (~\Git\etc\.my_functions):
namerep="$1"
new_repo() {
curl -X POST -u "iammultic:********************" -H "Content-Type: application/json" \
https://api.bitbucket.org/2.0/repositories/iammultic/$namerep \
-d '{ "scm": "git", "is_private": true, "project": {"key": "MAIN"}}' ;
cd /c/workspace ;
git clone git@bitbucket.org:iammultic/$namerep.git
}
Выполните в Git Bash команду:
$ git cr repo2
Все готово!
Проверьте создание нового репозитория в Bitbucket и создание локального репозитория в вашей рабочей директории на локальной машине.
Все примеры работающие, проверенные – можно использовать в работе с Git и BitBucket. И вы можете создать больше полезных для себя alias-ов и применять их, чтобы не тратить много времени на ведение и контроль версии файлов.
If you are using Git Bash on Windows and you’re used to Linux bash commands, chances are that you’d like to add aliases that help making your jobs easier.
These two are my favorite aliases:
$ alias cll='clear; ls -lah'
$ alias countFiles='ls -1 | wc -l'
Enter fullscreen mode
Exit fullscreen mode
How to add an alias permanently for the Git Bash
-
To add an alias permanently, you’d need to edit the file
/C/Program Files/Git/etc/profile.d/aliases.sh . -
Run your text editor as an administrator and open that file.
-
Add your alias and save the file.
-
Open the Git Bash. Execute ‘alias’, and you’re done. Have fun.
$ alias
alias cll='clear; ls -lah'
alias countFiles='ls -1 | wc -l'
alias ll='ls -lah'
alias ls='ls -F --color=auto --show-control-chars'
Enter fullscreen mode
Exit fullscreen mode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# create a file C:\Users\[user]\.bashrc | |
# add this content | |
# add your onw aliases or changes these ones as you like | |
# to make a dot (.bashrs) file in windows, create a file «.bashrs.» (without extention) and save. windows will save it as «.bashrc» | |
alias ls=‘ls -alh‘ | |
alias cdnginx=‘cd /c/nginx && ls‘ | |
alias cdmcga=‘cd /c/Users/[user]/sbox/node/mcga && ls‘ | |
alias cdfood9=‘cd /c/Users/[user]/sbox/node/food9 && ls‘ | |
alias cdmysql=‘cd /c/nginx/mysql/bin && ls‘ | |
alias cdsbox=‘cd /c/Users/[user]/sbox && ls‘ | |
alias cdangular=‘cd /c/Users/[user]/sbox/angularjs && ls‘ | |
alias cdmongobin=‘cd «/c/Program Files/MongoDB/Server/3.0/bin» && ls‘ | |
alias cdmongodata=‘cd /c/mongodb/data/db && ls‘ | |
alias sbrc=‘cd ~ && source .bashrc‘ | |
alias mydocs=‘cd ~/Documents‘ |
2.7 Git Basics — Git Aliases
Before we move on to the next chapter, we want to introduce a feature that can make your Git experience simpler, easier, and more familiar: aliases.
For clarity’s sake, we won’t be using them anywhere else in this book, but if you go on to use Git with any regularity, aliases are something you should know about.
Git doesn’t automatically infer your command if you type it in partially.
If you don’t want to type the entire text of each of the Git commands, you can easily set up an alias for each command using git config
.
Here are a couple of examples you may want to set up:
$ git config --global alias.co checkout
$ git config --global alias.br branch
$ git config --global alias.ci commit
$ git config --global alias.st status
This means that, for example, instead of typing git commit
, you just need to type git ci
.
As you go on using Git, you’ll probably use other commands frequently as well; don’t hesitate to create new aliases.
This technique can also be very useful in creating commands that you think should exist.
For example, to correct the usability problem you encountered with unstaging a file, you can add your own unstage alias to Git:
$ git config --global alias.unstage 'reset HEAD --'
This makes the following two commands equivalent:
$ git unstage fileA
$ git reset HEAD -- fileA
This seems a bit clearer.
It’s also common to add a last
command, like this:
$ git config --global alias.last 'log -1 HEAD'
This way, you can see the last commit easily:
$ git last
commit 66938dae3329c7aebe598c2246a8e6af90d04646
Author: Josh Goebel <dreamer3@example.com>
Date: Tue Aug 26 19:48:51 2008 +0800
Test for current head
Signed-off-by: Scott Chacon <schacon@example.com>
As you can tell, Git simply replaces the new command with whatever you alias it for.
However, maybe you want to run an external command, rather than a Git subcommand.
In that case, you start the command with a !
character.
This is useful if you write your own tools that work with a Git repository.
We can demonstrate by aliasing git visual
to run gitk
:
$ git config --global alias.visual '!gitk'
A Git Bash alias is a shorthand command that allows users to create custom shortcuts for frequently used Git commands, enhancing efficiency and saving time.
git config --global alias.co checkout
Understanding Bash Aliases
What is a Bash Alias?
A Bash alias is a shortcut or abbreviation for a longer command. Aliases help streamline workflows, allowing you to type less and execute frequently used commands with ease. For instance, instead of typing an entire command every time, you can simply define a short alias that corresponds to it.
Why Use Aliases in Git?
Using aliases in Git can significantly enhance your efficiency by transforming lengthy or complex commands into quick, memorable shortcuts. For example, rather than typing out `git status`, you can create a simple alias like `git st`, saving you time and keystrokes over the day.
Mastering Git Bash Bashrc: A Quick Guide
Creating Your First Git Bash Alias
Step-by-Step Guide to Creating an Alias
To create an alias, you use the `alias` command followed by the desired alias name and the command it should represent. The syntax is straightforward:
alias alias_name='command_to_run'
This structure allows you to assign your own shortcuts for commands you use frequently, making your Git experience smoother and faster.
Example of a Simple Alias
A very common alias in Git is setting `git st` for `git status`. This is how you can set it up:
alias st='git status'
This command tells your terminal to interpret `st` as the command `git status`. Anytime you need to check the status of your Git repository, you can simply type `st`, and the terminal will execute `git status`.
Master Bash Alias for Quick Command Access
Managing Your Aliases
Viewing Existing Aliases
To see a list of the aliases you currently have set up, simply type:
alias
Running this command will display all defined aliases, helping you quickly review what’s available.
Modifying and Removing Aliases
To edit an alias, just redefine it with the `alias` command using the same alias name. For example, if you want to change what `st` does, you can redefine it like this:
alias st='git status -s'
If you ever decide to remove an alias, you simply use the `unalias` command:
unalias alias_name
This is particularly useful if you want to clean up your alias list or replace an old command with a new one.
Mastering Git Bash Sequence: A Quick Guide
Storing Your Aliases Permanently
Using .bashrc or .bash_profile
By default, aliases are temporary; they last only for the duration of your terminal session. To make your aliases permanent, you need to add them to your `.bashrc` or `.bash_profile` file, which are scripts that run whenever you start a new terminal session. The choice between these two files usually depends on your environment and personal preference, but `.bashrc` is commonly used for aliases.
Adding Aliases to the Configuration File
To add your aliases into your configuration file, follow these steps:
-
Open your `.bashrc` file with your preferred text editor:
nano ~/.bashrc
-
Add your alias commands, like:
alias st='git status' alias cm='git commit -m'
-
Save the file and exit the editor.
-
To apply these changes immediately, use:
source ~/.bashrc
By sourcing the file, all the aliases you defined will be available in your current terminal session.
Git Bash Login: Mastering Your Command Line Credentials
Advanced Git Bash Aliases
Creating Multi-Command Aliases
Sometimes, you may want to run multiple commands with a single alias. This can be done using the `&&` operator, which executes the next command only if the previous one succeeded:
alias gs='git status && git branch'
With this alias, you can check the status of your repository and immediately view the branches in one go, saving time and effort.
Using Functions as Aliases
For more complex operations, aliases might not be sufficient. In such cases, using a function can provide more flexibility. For instance, if you frequently commit with a message, you might want to create a function:
function gcm() {
git commit -m "$1"
}
This function allows you to run `gcm «Your commit message»` to commit changes using your provided message as a parameter, which is particularly useful for standardizing commit messages.
Speed Up Your Workflow: Git Bash Slow Solutions
Best Practices for Using Git Bash Aliases
Keep It Simple
When creating aliases, simplicity is key. Ensure your naming conventions are clear and meaningful. This way, you won’t have to recall what each alias represents later. A good practice is to associate the alias with a common command, like `git co` for `git checkout`.
Regularly Review and Update Your Aliases
It’s important to periodically review your aliases to ensure they still serve your needs. As your projects evolve or your habits change, some aliases may become obsolete while you may need to add new ones. Keeping your alias list clean and relevant enhances both efficiency and usability.
Mastering Git Bash Sequence U001 for Quick Command Skills
Troubleshooting Common Issues
Common Problems When Creating Aliases
Sometimes, you might encounter issues where an alias does not work as expected. Common problems include incorrect syntax or conflicts with existing commands. Always double-check the syntax you used and ensure that the alias does not overlap with existing commands or functions.
Tips for Debugging
If you’re unsure why an alias isn’t working, a good debugging step is to use the `echo` command. For instance, you can test an alias like this:
alias ls='ls -lah' # Test with echo: echo $ls
Running `echo $ls` will show you the command your alias resolves to, allowing you to verify its correctness.
Bash Alias with Arguments: Simplify Your Command Line
Conclusion
Managing your Git Bash aliases effectively is essential for maximizing your productivity. By simplifying complex commands, you save time and reduce errors in your workflow. Take the time to personalize your alias list based on your frequently used commands and watch how it transforms your command-line experience. Embrace the power of aliases and enjoy a more efficient way to use Git in your development projects.
Git Bash Change Directory: Navigate Like a Pro
Additional Resources
For further learning, consider exploring the official Git documentation, online forums, and communities focused on Bash and Git. These resources provide a wealth of knowledge that can help you deepen your understanding and skills in command-line usage.