Doug
Doug

Reputation: 1714

Chaining system commands onto git commands

I'm trying to chain system commands in bash onto my git commands.

For instance: git commit -m cat commit_message.txt.

I've noticed I use the exact same 4 commands repeatedly, and I'd like to create an alias that does:

git add -A && git commit -m cat ~/my_project/commit_message.txt && git push origin dev && git push heroku-staging master.

I like to keep a log of the changes I make to my app in my commit_message.txt file, and update it each time I make a change, so it'd be ideal if I could just read this log from the terminal every time I want to commit a change.

I am by no means a terminal wizard, so I'm hoping this is an easy solution that I haven't come across yet. I've searched quite a bit, and haven't found a similar use.

Upvotes: 1

Views: 543

Answers (4)

jeremy-denis
jeremy-denis

Reputation: 6878

to create a system alias you can do :

alias myName=myCommand

or if you want only a session alias (only available during your terminal alive) you can do :

myName=myCommand 

To launch it you can do $myName

then to launch several command you can try to use pipe :

command 1 | command 2 ...

Upvotes: 0

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

You can just write a script.

Create $HOME/bin directory for your executables:

mkdir -p ~/bin

Add the directory to $PATH within your ~/.bashrc.

export PATH=$PATH:$HOME/bin

Update the environment in the current terminal session:

source ~/.bashrc

Create the script:

git_commit_file="$HOME/bin/git-commit"
cat > "$git_commit_file" <<'EOS'
#!/bin/bash -
message_file="$1"
# Add your commands here ...
EOS
chmod +x $git_commit_file

Now you can run git-commit message.txt.

By the way, creating aliases is as simple as adding an alias name=command in ~/.bashrc, e.g.:

alias ls='ls --color=auto'

But I'd recommend writing a script.

Upvotes: 1

Matthieu Moy
Matthieu Moy

Reputation: 16527

git commit has a -F (--file) that does exactly what you want, without using any shell magic: just use git commit -F commit_message.txt.

Upvotes: 4

Andreas Louv
Andreas Louv

Reputation: 47099

You need command substitution for using output from one command as an argument for another:

git commit -m "$(< commit_message.txt)"

You can also use git commit -a to add all files so no need to call git add:

git commit -am "$(< commit_message.txt)"

I would create a function for it:

do_git_stuff() {
  # Du stuff...
  : # The colon is here because a function cannot be empty. This can be removed when you
    # add some "real" code
}

To tie it together:

do_git_stuff() {
  git commit -am "$(< commit_message.txt)" \
    && git push origin dev \
    && git push heroku-staging master
}

What is "$(< file.txt)"?

The < operator means that you should take stdin from file.txt. A command substitution ($(...)) will return what is written to stdout. The quotes are used to avoid word splitting.

Upvotes: 2

Related Questions