Bash - check if repository exists - bash

I am trying to create if statement which will check if repository with name X exists, if it doesn't => create it.
Made following code. It works, but when repository doesn't exists, then it shows error. I couldn't find any ways of removing that error in console. Make I was using &>/dev/null not in correct way...
myStr=$(git ls-remote https://github.com/user/repository);
if [ -z $myStr ]
then
echo "OMG IT WORKED"
fi

As soon as you completely silence git ls-remote I will suggest to check the exit code of the command ($?) rather than its output.
Based on your code you could consider a function in this way:
check_repo_exists() {
repoUrl="$1"
myStr="$(git ls-remote -q "$repoUrl" &> /dev/null)";
if [[ "$?" -eq 0 ]]
then
echo "REPO EXISTS"
else
echo "REPO DOES NOT EXIST"
fi
}
check_repo_exists "https://github.com/kubernetes"
# REPO DOES NOT EXIST
check_repo_exists "https://github.com/kubernetes/kubectl"
# REPO EXISTS

Related

While loop with if statement plus result of variable

I was doing a script for myself to summarize commands I use daily in one handy script. So basically I ended doing it with a conditional checking if the .git folder exists first but I'd like to make it more interesting and like so understand better the loop. My desire is to have a variable like:
"output=$(git status)" and if the result is 0, continue depending on the statement. If the result is other than 0, break the loop and end the script with a message like "the actual directory hasn't a .git repo".
I let you my first idea of it but without the git status as I don't know how to add it neither where to. Thank you guys!
set -e
gitrepo=true
while [ $gitrepo == true ]; do
if [[ $? -ne 0 ]]; then
echo "not a git directory"
$gitrepo=false
else
read -p "Commit message: " commit
git commit -am "$commit"
fi
done
Try this: I did as Cyrus suggested:
#!/usr/bin/env bash
set -e
gitrepo=True
while [[ $gitrepo ]]; do
if [[ ! $? ]]; then
echo "not a git directory"
gitrepo=False
else
read -p "Commit message: " -r commit
git commit -am "$commit"
exit 0
fi
done

bash check if a variable starts with 'fatal'

I have a variable in bash:
branchName=$(git branch --show-current)
There are two options for the returned value:
banch name (e.g. master)
fatal: not a git repository (or any of the parent directories): .git
I want to check if branchName starts with fatal:
I have tried to check if it starts with master and it works:
if [[ $branchName == master* ]];
then echo "yes"
fi
echo $branchName
Output:
yes
master
but when I try to check if it starts with fatal: it does not work:
if [[ $branchName == fatal* ]];
then echo "yes"
fi
Output:
fatal: not a git repository (or any of the parent directories): .git
but when I try to check if it starts with fatal: it does not work:
It's because this is an error message and goes to stderr. What you capture is only the stdout.
A better approach is to check the return value instead. E.g.
if branchName=$(git branch --show-current 2>/dev/null); then
echo "Branch is: $branchName"
else
echo "Error: can't get branch name"
fi
(If command succeeds, it'd return 0; any non-zero value is usually treated as failure. The if statement above would be "true" when git return 0).
But if you do want to capture stderr, you can do:
branchName=$(git branch --show-current 2>&1)

How to check file exists via Bash script?

I'm trying to clone a repo and test it after is done via bash script. I have written my test code based on Bash Shell: Check File Exists or Not.
#!/bin/bash
echo "*** TRY TO INIT INFER ***"
# Clone Infer
INFER_GIT_PATH="https://github.com/facebook/infer.git"
echo "> Try to Clone Infer from ${INFER_GIT_PATH}"
git clone ${INFER_GIT_PATH}
INFER_PATH="/infer/infer/bin/infer"
[ -e ${INFER_PATH} ] && echo "Infer downloaded successfully" || echo "Something went wrong :("
Although repo can be downloaded successfully and /infer/infer/bin/infer.sh exists, I'm always getting Something went wrong :( message.
Change it to this (use a relative path):
INFER_PATH="./infer/infer/bin/infer"
[ -e ${INFER_PATH} ] && echo "Infer downloaded successfully" || echo "Something went wrong :("
and it should work.
If you want to know if a file exist, you can use -f flag:
[ -f /infer/infer/bin/infer ] && echo "Infer downloaded successfully" || echo "Something went wrong :("

Capture output from git command?

I am writing a script to automate setting up new projects for me.
this includes pulling down a github repository.
What I want to do is have some output from my script, then call git clone $repo
I want to show the output from that command while it is running, but then when it has run if it has run successfully replace it's output (note just the git commands output, I still want the output from before that to be there) with repository successfully cloned and if failed just leave the output there, and print repository cloning failed.
How can I do this?
Below is my current (rather simple) script.
#! /bin/bash
# -p project name
templateurl="git#bitbucket.org:xxx/xxx-site-template.git"
while getopts ":p:" opt; do #eventually I'll add more options here
case $opt in
p)
project=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
if [ -z "$project" ]; then
echo "Project name required"
exit 1
fi
clear
echo "|==========================|"
echo "| New xxx Project Creator |"
echo "|==========================|"
echo "Project: $project"
if [ -d "$project" ]; then
echo "Directory $project already exists!"
exit 1
fi
mkdir $project
if [ ! -d "$project" ]; then
echo "Failed to create project directory!"
exit 1
fi
echo "Cloning xxx Template repository"
git clone $templateurl $project
git clone does provide a exit code you can read with $? like follows:
git clone user#server:repo
echo $?
This will print 0 if everything worked just fine. If for example the folder is not a git repository you will get the exit code 128.
you can check if the clone worked as follows:
git clone user#server:repo localrepo --quiet
success=$?
if [[ $success -eq 0 ]];
then
echo "Repository successfully cloned."
else
echo "Something went wrong!"
fi
--quietwill suppress any output from git, as long as there are no errors. So if you just remove the else-branch you will get you positive output or the error produced by git.
git clone user#server:repo localrepo > git.log 2>&1
if [[ $? eq 0 ]];
then
echo Repository successfully cloned.
else
cat git.log
echo Repository cloning failed.
fi
rm git.log
Explanation:
git clone user#server:repo localrepo > git.log 2>&1
Redirects stdout and stderr streams to git.log. > git.log redirects stdout to git.log 2>&1 redirects stderr to the same place as stdout(thus, git.log).
$? eq 0 Checks the retcode of git which should be 0 if the clone was successful.
cat git.log outputs the contents of the git.log file.

unexpected operator [: git: in bourne shell script 'if' conditional statement

I've watched an excellent shell scripting course through a multitude of videos. Now that I think I am fairly familiar with the Bourne shell, I decided to write my first shell script.
Script goal: check if git working directory is clean. If so, overwrite working directory to a branch named deployment. Finally, push the deployment branch to origin.
I ended up with this code:
#!/bin/sh
######################################################
# Deploys working directory to git deployment branch.
# Requires that the working directory is clean.
######################################################
#check if the working directory is clean
if [ git diff-index --quiet HEAD ]
then
if [ git branch -f deployment ]
then
if [ git push origin deployment ]
then
echo
echo "OK. Successfully deployed to git deployment branch."
echo
exit 0 #success
else
echo
echo "Error: failed to push deployment branch to origin."
echo
exit 1 #failure
fi
else
echo
echo "Error: failed to create or overwrite deployment branch."
echo
exit 1 #failure
fi
else
echo
git status #show the status of the working directory
echo
echo "Error: working directory is not clean. Commit your changes first..."
echo
exit 1 #failure
fi
Unfortunately, this seems to give me an error: ./tools/deploygit: 9: [: git: unexpected operator
Why is this so? What operator am I using in if [ git diff-index --quiet HEAD ] that is unexpected?
As a bonus, do you have any suggestions or tips on how to improve the efficiency, logic or readability of this script?
In this statement:
if [ git diff-index --quiet HEAD ]
The [ is an alias for the test command, so what you're actually running is...
if test git diff-index --quiet HEAD ]
...which isn't what you mean. You don't need to use the test command in order to evaluate the result of a command; you should just do this:
if git diff-index --quiet HEAD
Take a look at the documentation for the if command:
$ help if
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
The conditional argument to the if statement is command. Normally, the test command is used to make it look like other languages, but you can put any command there. Things that exit with a return code of 0 evaluate to true and anything else evaluates to false.

Resources