Bash Shell: Passing in arguments to build a reusable command

Aliases are great, but it sucks when you need to mix arguments into certain parts of the command rather than after the alias itself.

There are some things we type on a regular basis which cant be put into aliases. An example would be the command I use to clone from git.

git clone git@git.server.com:git_project_name.git clone_name

I would of liked to use an alias in this way:

alias_name git_project_name clone_name

But when executed, it'll come out as:

git clone git@git.server.com:.git git_project_name clone_name

For this, I've resorted to writing a script called "clone_git.sh".

#! /bin/bash
# script to git clone

PROJECT=$1
shift
SEARCH="git clone git@git.server.com:$PROJECT.git $@"

echo $SEARCH
$SEARCH

Using the script with this syntax:

./clone_git.sh project_name clone_name arg1 arg2 arg3

Will produce:

git clone git@git.server.com:project_name.git clone_name arg1 arg2 arg3

The shift command removes the first argument off the list, so "project_name" will be removed from "$@".

Now if you dont require a variable number of arguments, you can simplify the script by removing the $PROJECT variable, removing shift and replacing "$@" with "$2".

The script will now look like:

#! /bin/bash
# script to git clone

SEARCH="git clone git@git.server.com:$1.git $2"

echo $SEARCH
$SEARCH

Calling the script with the same syntax will now produce:

git clone git@git.server.com:project_name.git clone_name

[ Sources: $@ and Shift ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog