how to run a shell script as an alias? - shell

I wanna alias a script to my zsh. Aliasing a script in zshrc does not work, the output of the script in nothing
There are no syntax errors in my script. i have tried running
"sh ./script.sh" in the script containing folder which does fetches the desired result but alias something="sh ~/script.sh" does not work
even alias something="source ~/script.sh" does not work
the script creates a local project and a github repo
contents of the script:
#!/bin/bash
function create () {
read -p 'Repository Name: ' uservar
projects_directory = ~/Downloads/Projects/ #change this path to the directory where you want to store you files
mkdir $projects_directory/$uservar
cd $projects_directory/$uservar
git init
touch README.md
echo -e "#$uservar" >> $projects_directory/$uservar/README.md
# this is where we make a github repo from cli
repo_name=$uservar
test -z $repo_name && echo "Repo name required." 1>&2 && exit 1
curl -u 'thisisshub' https://api.github.com/user/repos -d "{\"name\":\"$repo_name\"}" #change thisisshub to your <username>
#making a git repo from cli ends
git add .
git commit -m "Initial Commit"
git push -u origin master
code .
}
expected result: successful aliasing of a script
actual result: no output

Related

bash, script to git add one file and commit

I'm trying to create a script to do this:
git add "file"
git commit -m "Comment"
My idea is to run:
gac "file" "Comment"
I know I can do something similar but for all files, with:
echo 'alias gac="/path/to/gitaddcommit.sh"' >> ~/.bash_profile
And the .sh would be:
!/bin/bash
git add .
echo “Enter commit message: “
git commit -am “$commitMessage”
Well you need two things :
A bin folder where you can put every sh script you want to use everywhere.
More knowledge about shell scripting and how you can get argv (in your ex: 'file' 'Comment')
So first go to your /home/<username> then mkdir bin && cd bin && pwd
then copy the pwd and add it into your PATH env variable inside your .bashrc
path example: PATH='/bin/:/sbin/:/home//bin
Then source ~/.bashrc you can now use every sh script inside you bin folder everywhere.
Cool so first problem done !
you don't have to do echo alias gac="/path/to/gitaddcommit.sh"' >> ~/.bash_profile anymore.
Now second problem here a post that can help you post
And let me show you for your example :
cd ~/bin && vi gac.sh
Now the script :
#!/bin/sh
if [ "$#" -ne 2 ]; then
echo "Usage: ./gac FILENAME COMMIT_MESSAGE" >&2
exit 1
fi
git add "$1"
git commit -am "$2"
First we check the number or arg then git add and commit.
Simple and fast maybe checking if arg one is a file might be a good idea too.
PS: i'm going to re write my post ahah
Here's what I have in my .bashrc:
ga ()
{
if test "$1" != "-f" && git rev-parse HEAD > /dev/null 2>&1 && ! git diff-index --quiet HEAD; then
echo 'Repo is dirty. -f to force' 1>&2;
return 1;
fi;
git add "$#";
list=$(git diff --name-only --cached | tr \\n \ );
git commit -m "Add $list"
}
The commit message is autogenerated, but you could easily modify it to prompt the user or take it from somewhere else.

Automating git push and commit in a shell script on a Centos server

I am implementing a shell script that will be backing up the database and then push the sql file to Github, I am using centos server the project is located at /opt/server-scripts/backup.sh. How do I automate this?
Here is my implementation so far:
#!/bin/bash/
var=$CURRENT_DATE=date +"%D %T"
docker exec 3856a8e52031 /usr/bin/mysqldump -u root --password=cvxxx django_mysql_docker > backup.sql
# Git Push
GIT=$(which git)
REPO_DIR=/opt/server-scripts/
cd ${REPO_DIR} || exit
${GIT} add --all .
${GIT} commit -m "backup:" + "'$CURRENT_DATE'"
${GIT} https://pmutua:xxxxx#github.com/pmutua/sqlbackup.git master
You can check if a command/executable is installed or it is with in your PATH, one way using type
if type -P git >/dev/null; then
echo 'git is installed.'
fi
If you want to negate the result add the !
if ! type -P git >/dev/null; then
echo 'git is not installed.'
fi
To add that to your script.
#!/usr/bin/env bash
docker exec 3856a8e52031 /usr/bin/mysqldump -u root --password=cvxxx django_mysql_docker > backup.sql
if ! type -P git >/dev/null; then ##: Check if git is not installed
echo 'git is not installed.' >&2 ##: print an error message to stderr
exit 1 ##: Exit with an error
fi
# Git Push
CURRENT_DATE=$(date +"%D %T") ##: Assign the output of date in a variable
REPO_DIR=/opt/server-scripts/
cd "${REPO_DIR}" || exit
git add --all .
git commit -m "backup: '$CURRENT_DATE'"
git push https://pmutua:xxxxx#github.com/pmutua/sqlbackup.git master
You can add the date directly git commit -m "backup: '$(date +"%D %T")'"
that way the date will be same with the output of git log
Other ways to check if a command exists is via command and hash see Howto check if a program exists in my PATH

Git - How to make custom alias function always available?

I have a script that I've made that creates a repository locally, creates first commit and creates the remote repo. Here it is:
#!/bin/bash
function create-repo {
inside_git_repo="$(git rev-parse --is-inside-work-tree 2>/dev/null)"
# check if we already inside a repository
if [ "$inside_git_repo" = true ]; then
echo "Error: It is not possible to create a repository inside another one"
else
#check if the name of repository is not null
if [ "$1" = "" ]; then
echo "Error: Missing one argument (Repository name)"
else
#creating repository folder
echo "Repo will be created with the following name: $1 "
mkdir "$1"
cd "$1" || exit 1
echo
#Create a README.md file to push to remote
echo "# $1" >> README.md
echo
#initializing repo
git init
echo
#staging and commiting README.md file
git add README.md
git commit -m "first commit"
echo
#username in github
username="alanwilliam"
#secret token of github API
token="PUT HERE YOU SECRET TOKEN"
#json that will be sent to github API
json="{ \"name\":\"$1\" }"
#Curl command that does the magic to create the remote on github
curl --user "$username":"$token" --request POST -H "Content-Type: application/json" -d "$json" https://api.github.com/user/repos
echo
echo
echo
#adding remote and pushing
git remote add origin https://github.com/alanwilliam/"$1".git
git push -u origin master
fi
fi
}
This code is working just fine - it is perfect for me. I've put it inside a file called .custom_aliases and it worked. However, in order to git detect this file and make the command available, every time that I open git bash, I need to type
source ~/.custom_aliases to be able to use the command in script, which is annoying.
Is there a way to make it always available, so I don't have to type the source command every time I open git bash?

Bash: Bad subtitution error in a for loop - git tags

I am trying to execute a migration from SVN to GIT using git svn clone .. and everything works smoothly.
Now i need to transform the tags in SVN to real tags in git using this command
for t in $(git for-each-ref --format='%(refname:short)' refs/remotes/origin/tags)
do
git tag ${t/origin\/tags\//} $t - #BAD substitution error - need to fix
git branch -D -r $t
done
If i run this script in my commandline it works, but if i run this script in a shell script it will fail with a "Bad substitution error" . Any advice here?
The full script is here:
#!/bin/bash
## Modificed script - Fork from https://github.com/MPDFT/svn-to-git
####### Project name
PROJECT_NAME="" #Example - Digisharp
SVN_USERNAME="" #Example - adys
GIT_USERNAME="" #Example - adys
GIT_CREDENTIAL="" #Example - pz2fekhjcsq5io5xbslcuss5lspo4lcgh4cwjswge265uzxrnzxv
####### SVN
# SVN repository to be migrated
SVN_URL="" #Example -
####### GIT
# Git repository to migrate - IMPORTANT! YOU MUST INCLUDE YOUR USERNAME AND PASSWORD(PAT TOKEN FOR AZURE)
# We need this to automate the git push without having it asking you for password
GIT_URL="" #Example -
###########################
#### Don't need to change from here
###########################
#STYLE_COLOR
RED='\033[0;31m'
LIGHT_GREEN='\e[1;32m'
NC='\033[0m' # No Color
echo -e "${LIGHT_GREEN} [LOG] Starting migration of ${NC}" $SVN_TRUNK
echo -e "${LIGHT_GREEN} [LOG] Using: ${NC}" $(git --version)
echo -e "${LIGHT_GREEN} [LOG] Using: ${NC}" $(svn --version | grep svn,)
echo -e "${LIGHT_GREEN} [LOG] Step 01/05 Create Directories ${NC}"
echo -e "${LIGHT_GREEN} [RUN] Step 02/05 ${NC} £ git svn clone --stdlayout --no-minimize-url $BASE_SVN $PROJECT_NAME --user=$SVN_USERNAME"
git svn clone --stdlayout --no-minimize-url $SVN_URL $PROJECT_NAME --user=$SVN_USERNAME --authors-file=authors.txt
cd $PROJECT_NAME
echo -e "${LIGHT_GREEN} [RUN] Step 03/05 ${NC} $ git remote add origin"
git remote add origin $GIT_URL
echo -e "${LIGHT_GREEN} [RUN] Step 04/05 ${NC} - Preparing the git branches and tags"
for t in $(git for-each-ref --format='%(refname:short)' refs/remotes/origin/tags)
do
#git tag ${t/origin\/tags\//} $t - BAD substitution error - need to fix
git branch -D -r $t
done
for b in $(git for-each-ref --format='%(refname:short)' refs/remotes)
do
git branch $b refs/remotes/$b
git branch -D -r $b
done
echo -e "${LIGHT_GREEN} [RUN] Step 05/05 [RUN] git push ${NC}"
git push origin --all
git push origin --tags
echo "Successful - The git repository is now available in" $GIT_URL
I run the command with sh migration.sh
Are you executing your script with something like /bin/sh /path/to/script.sh?
${t/origin\/tags\//} is available in bash but isn't POSIX shell compatible, you might have success chancing it to something like:
echo "$t" | sed 's~origin/tags/~~'
I would highly recommend linting your script with shellcheck, as you got a few potential errors.
I run the command with sh migration.sh.
${var/search/replacement} is a bash feature. Running sh explicitly means the #!/bin/bash shebang line is ignored. Never run scripts that way.
There's no need to edit the script to remove the bashisms. Just run it with ./migration.sh so the shebang is respected.
$ ./migration.sh

Bash script to change parent shell directory [duplicate]

This question already has answers here:
Why can't I change directories using "cd" in a script?
(33 answers)
Closed 7 years ago.
What I'm trying to do
I've created a shell script that I've added to my $PATH that will download and get everything setup for a new Laravel project. I would like the script to end by changing my terminal directory into the new project folder.
From what I understand right now currently it's only changing the directory of the sub shell where the script is actually running. I can't seem to figure out how to do this. Any help is appreciated. Thank you!
#! /usr/bin/env bash
echo -e '\033[1;30m=========================================='
## check for a directory
if test -z "$1"; then
echo -e ' \033[0;31m✖ Please provide a directory name'
exit
fi
## check if directory already exist
if [ ! -d $1 ]; then
mkdir $1
else
echo -e ' \033[0;31m✖ The '"$1"' directory already exists'
exit
fi
# move to directory
cd $1
## Download Laravel
echo -e ' \033[0;32m+ \033[0mDownloading Laravel...'
curl -s -L https://github.com/laravel/laravel/zipball/master > laravel.zip
## Unzip, move, and clean up Laravel
echo -e ' \033[0;32m+ \033[0mUnzipping and cleaning up files...'
unzip -q laravel.zip
rm laravel.zip
cd *-laravel-*
mv * ..
cd ..
rm -R *-laravel-*
## Make the /storage directory writable
echo -e ' \033[0;32m+ \033[0mMaking /storage directory writable...'
chmod -R o+w storage
## Download and install the Generators
echo -e ' \033[0;32m+ \033[0mInstalling Generators...'
curl -s -L https://raw.github.com/JeffreyWay/Laravel-Generator/master/generate.php > application/tasks/generate.php
## Update the application key
echo -e ' \033[0;32m+ \033[0mUpdating Application Key...'
MD5=`date +”%N” | md5`
sed -ie 's/YourSecretKeyGoesHere!/'"$MD5"'/' application/config/application.php
rm application/config/application.phpe
## Create .gitignore and initial git if -git is passed
if [ "$2" == "-git" ]; then
echo -e ' \033[0;32m+ \033[0mInitiating git...'
touch .gitignore
curl -s -L https://raw.github.com/gist/4223565/be9f8e85f74a92c95e615ad1649c8d773e908036/.gitignore > .gitignore
# Create a local git repo
git init --quiet
git add * .gitignore
git commit -m 'Initial commit.' --quiet
fi
echo -e '\033[1;30m=========================================='
echo -e ' \033[0;32m✔ Laravel Setup Complete\033[0m'
## Change parent shell directory to new directory
## Currently it's only changing in the sub shell
filepath=`pwd`
cd "$filepath"
You can technically source your script to run it in your parent shell instead of spawning a subshell to run it. This way whatever changes you make to your current shell (including changing directories) persist.
source /path/to/my/script/script
or
. /path/to/my/script/script
But sourcing has its own dangers, use carefully.
(Peripherally related: how to use scripts to change directories)
Use a shell function to front-end your script
setup () {
# first, call your big script.
# (It could be open-coded here but that might be a bit ugly.)
# then finally...
cd someplace
}
Put the shell function in a shell startup file.
Child processes (including shells) cannot change current directory of parent process. Typical solution is using eval in the parent shell. In shell script echo commands you want to run by parent shell:
echo "cd $filepath"
In parent shell, you can kick the shell script with eval:
eval `sh foo.sh`
Note that all standard output will be executed as shell commands. Messages should output to standard error:
echo "Some messages" >&2
command ... >&2
This can't be done. Use exec to open a new shell in the appropriate directory, replacing the script interpreter.
exec bash
I suppose one possibility would be to make sure that the only output of your script is the path name you want to end up in, and then do:
cd `/path/to/my/script`
There's no way your script can directly affect the environment (including it's current directory) of its parent shell, but this would request that the parent shell itself change directories based on the output of the script...

Resources