I am attempting to load my git aliases from a gist on github. For some reason, the command executes find, but when I attempt to execute any of the aliases, they are either incorrectly mapped — e.g., gsts -> git stash instead of gsts -> git status — or they are not mapped at all.
#!/bin/bash
update_git_aliases(){
GIST_URL='https://gist.githubusercontent.com/Moyoka22/ec605b0b52fee6d6d30d5f72822938f4/raw/git-aliases'
RESPONSE="$(wget --no-cache -qO- ${GIST_URL})"
if [ ${?} -ne 0 ]
then
echo 'Download failed. Exiting.'
return 1
fi
echo ${RESPONSE} > ${1}
chmod +x ${1}
}
DOWNLOAD_FAILED=0
ALIAS_FILE="${HOME}/.config/git-aliases"
if [ ! -f ${ALIAS_FILE} ]
then
echo "Git aliases not found! Downloading..."
update_git_aliases ${ALIAS_FILE}
DOWNLOAD_FAILED=${?}
fi
if [ ${DOWNLOAD_FAILED} -ne 0 ]
then
echo "Downloading aliases failed."
exit 1
fi
cat ${ALIAS_FILE} | bash
I assume you want the aliases on your interactive shell, so remove the last cat as it's useless and once ${HOME}/.config/git-aliases is created
$ source "${HOME}/.config/git-aliases"
The alias commands must be run in your current shell process to have an effect.
cat ${ALIAS_FILE} | bash executes the alias commands in ALIAS_FILE in a new child process, not your shell, and not the program's shell.
source runs the commands in the current shell. You need to source the file from your current shell, not from the program. You can do this after the file is updated. In order to make this permanent, you will need to add source "${HOME}/.config/git-aliases" to your shell config.
What many programs like this do is print out the necessary commands at the end.
echo "$ALIAS_FILE updated"
echo "Make sure `source $ALIAS_FILE` is in your $HOME/.bash_profile"
echo "Run `source $ALIAS_FILE` to use it in your current shell"
I'm trying to create a shell script that I will download the latest Atomic gotroot rules to my server, unpack them, copy them to the correct folder, etc.,
I've been reading shell tutorials and forum posts for most of the day and the syntax escapes me for some of these. I have run all these commands and I know they work if I manually run them.
I know I need to develop some error checking, but I'm just trying to get the commands to run correctly. The main problem at the moment is the syntax of the wget commands, i've got errors about missing semi-colons, divide by zero, unsupported schemes - I've tried various quoting (single and double) and escaping - / " characters in various combinations.
Thanks for any help.
The raw wget command is
wget --user="jim" --password="xxx-yyy-zzz" "http://updates.atomicorp.com/channels/rules/subscription/VERSION"
#!/bin/sh
update_modsec_rules(){
wget=/usr/bin/wget
tar=/bin/tar
apachectl=/usr/bin/apache2ctl
TXT="Script Run Finished"
WORKING_DIR="/var/asl/updates"
TARGET_DIR="/usr/local/apache/conf/modsec_rules/"
EXISTING_FILES="/var/asl/updates/modsec/*"
EXISTING_ARCH="/var/asl/updates/modsec-*"
WGET_OPTS='--user=jim --password=xxx-yyy-zzz'
URL_BASE="http://updates.atomicorp.com/channels/rules/subscription"
# change to working directory and cleanup any downloaded files and extracted rules in modsec/ directory
cd $WORKING_DIR
rm -f $EXISTING_ARCH
rm -f $EXISTING_FILES
rm -f VERSION*
# wget to download VERSION file
$wget ${WGET_OPTS} "${URL_BASE}/VERSION"
# get current MODSEC_VERSION from VERSION file and save as variable
source VERSION
TARGET_DATE=$MODSEC_VERSION
echo $TARGET_DATE
# wget to download current archive
$wget ${WGET_OPTS} "${URL_BASE}/modsec-${TARGET_DATE}.tar.gz"
# extract archive
echo "extracting files . . . "
tar zxvf $WORKING_DIR/modsec-${TARGET_DATE}.tar.gz
echo "copying files . . . "
cp -uv $EXISTING_FILES $TARGET_DIR
echo $TXT
}
update_modsec_rules $# 2>&1 | tee -a /var/asl/modsec_update.log
RESTART_APACHE="/usr/local/cpanel/scripts/restartsrv httpd"
$RESTART_APACHE
Here are some guidelines to use when writing shell scripts.
Always quote variables when you use them. This helps avoid the possibility of misinterpretation. (What if a filename contains a space?)
Don't trust fileglobbing on commands like rm. Use for loops instead. (What if a filename starts with a hyphen?)
Avoid subshells when possible. Your lines with backquotes make me itchy.
Don't exec if you can help it. And especially don't expect any parts of your script after your exec to actually get run.
I should point out that while your shell may be bash, you've specified /bin/sh for execution of this script, so it is NOT a bash script.
Here's a rewrite with some error checking. Add salt to taste.
#!/bin/sh
# Linux
wget=/usr/bin/wget
tar=/bin/tar
apachectl=/usr/sbin/apache2ctl
# FreeBSD
#wget=/usr/local/bin/wget
#tar=/usr/bin/tar
#apachectl=/usr/local/sbin/apachectl
TXT="GOT TO THE END, YEAH"
WORKING_DIR="/var/asl/updates"
TARGET_DIR="/usr/local/apache/conf/modsec_rules/"
EXISTING_FILES_DIR="/var/asl/updates/modsec/"
EXISTING_ARCH="/var/asl/updates/"
URL_BASE="http://updates.atomicorp.com/channels/rules/subscription"
WGET_OPTS='--user="jim" --password="xxx-yyy-zzz"'
if [ ! -x "$wget" ]; then
echo "ERROR: No wget." >&2
exit 1
elif [ ! -x "$apachectl" ]; then
echo "ERROR: No apachectl." >&2
exit 1
elif [ ! -x "$tar" ]; then
echo "ERROR: Not in Kansas anymore, Toto." >&2
exit 1
fi
# change to working directory and cleanup any downloaded files
# and extracted rules in modsec/ directory
if ! cd "$WORKING_DIR"; then
echo "ERROR: can't access working directory ($WORKING_DIR)" >&2
exit 1
fi
# Delete each file in a loop.
for file in "$EXISTING_FILES_DIR"/* "$EXISTING_ARCH_DIR"/modsec-*; do
rm -f "$file"
done
# Move old VERSION out of the way.
mv VERSION VERSION-$$
# wget1 to download VERSION file (replaces WGET1)
if ! $wget $WGET_OPTS $URL_BASE}/VERSION; then
echo "ERROR: can't get VERSION" >&2
mv VERSION-$$ VERSION
exit 1
fi
# get current MODSEC_VERSION from VERSION file and save as variable,
# but DON'T blindly trust and run scripts from an external source.
if grep -q '^MODSEC_VERSION=' VERSION; then
TARGET_DATE="`sed -ne '/^MODSEC_VERSION=/{s/^[^=]*=//p;q;}' VERSION`"
echo "Target date: $TARGET_DATE"
fi
# Download current archive (replaces WGET2)
if ! $wget ${WGET_OPTS} "${URL_BASE}/modsec-$TARGET_DATE.tar.gz"; then
echo "ERROR: can't get archive" >&2
mv VERSION-$$ VERSION # Do this, don't do this, I don't know your needs.
exit 1
fi
# extract archive
if [ ! -f "$WORKING_DIR/modsec-${TARGET_DATE}.tar.gz" ]; then
echo "ERROR: I'm confused, where's my archive?" >&2
mv VERSION-$$ VERSION # Do this, don't do this, I don't know your needs.
exit 1
fi
tar zxvf "$WORKING_DIR/modsec-${TARGET_DATE}.tar.gz"
for file in "$EXISTING_FILES_DIR"/*; do
cp "$file" "$TARGET_DIR/"
done
# So far so good, so let's restart apache.
if $apachectl configtest; then
if $apachectl restart; then
# Success!
rm -f VERSION-$$
echo "$TXT"
else
echo "ERROR: PANIC! Apache didn't restart. Notify the authorities!" >&2
exit 3
fi
else
echo "ERROR: Apache configs are broken. We're still running, but you'd better fix this ASAP." >&2
exit 2
fi
Note that while I've rewritten this to be more sensible, there is certainly still a lot of room for improvement.
You have two options:
1- changing this to
WGET1=' --user="jim" --password="xxx-yyy-zzz" "http://updates.atomicorp.com/channels/rules/subscription/VERSION"'
then run
wget $WGET1 same to WGET2
Or
2- encapsulating $WGET1 with backquotes ``.
e.g.:
`$WGET`
This applies to any command your executing out of a variable.
Suggested changes:
#!/bin/sh
TXT="GOT TO THE END, YEAH"
WORKING_DIR="/var/asl/updates"
TARGET_DIR="/usr/local/apache/conf/modsec_rules/"
EXISTING_FILES="/var/asl/updates/modsec/*"
EXISTING_ARCH="/var/asl/updates/modsec-*"
WGET1='wget --user="jim" --password="xxx-yyy-zzz" "http://updates.atomicorp.com/channels/rules/subscription/VERSION"'
WGET2='wget --user="jim" --password="xxx-yyy-zzz" "http://updates.atomicorp.com/channels/rules/subscription/modsec-$TARGET_DATE.tar.gz"'
## change to working directory and cleanup any downloaded files and extracted rules in modsec/ directory
cd $WORKING_DIR
rm -f $EXISTING_ARCH
rm -f $EXISTING_FILES
## wget1 to download VERSION file
`$WGET1`
## get current MODSEC_VERSION from VERSION file and save as variable
source VERSION
TARGET_DATE=`echo $MODSEC_VERSION`
## WGET2 command to download current archive
`$WGET2`
## extract archive
tar zxvf $WORKING_DIR/modsec-$TARGET_DATE.tar.gz
cp $EXISTING_FILES $TARGET_DIR
## restart server
exec '/usr/local/cpanel/scripts/restartsrv_httpd' $*;
Pro Tip: If you need string substitution, using ${VAR} is much better to eliminate ambiguity, e.g.:
tar zxvf $WORKING_DIR/modsec-${TARGET_DATE}.tar.gz
I've been watching some of the Team Treehouse videos and they have a very nice looking terminal when working with Git.
For example they have (something similar):
mike#treehouseMac: [/Work/test - feature-branch-name] $ git add .
mike#treehouseMac: [/Work/test - feature-branch-name] $ git commit -m "Some feature."
mike#treehouseMac: [/Work/test - feature-branch-name] $ git checkout master
mike#treehouseMac: [/Work/test - master] $ git status
How can my terminal show me some useful information of what branch I'm on, with colors to distinguish bits of the data I want? Is there some sort of de-facto plugin I haven't found yet?
I'm using Mac OSX 10.8
For anyone looking for how to do this in macOS Catalina or above (10.15+ incl. Big Sur 11.0) which has deprecated bash in favour of zsh, here is my .zshrc file:
parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
COLOR_DEF='%f'
COLOR_USR='%F{243}'
COLOR_DIR='%F{197}'
COLOR_GIT='%F{39}'
NEWLINE=$'\n'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n#%M ${COLOR_DIR}%d ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF}${NEWLINE}%% '
If you don't like the colours I have used, replace the 243/197/39 values with the colour codes as defined here:
https://misc.flogisoft.com/bash/tip_colors_and_formatting
Simple way
Open ~/.bash_profile in your favorite editor and add the following content to the bottom.
Git branch in prompt.
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u#\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "
Add Git Branch To Terminal Prompt (Mac)
It's not about a plugin. It's about prompt tricks in the shell.
For a cool setup in bash, check out the dotfiles project of this guy:
https://github.com/mathiasbynens/dotfiles
To get a fancy prompt, include the .bash_prompt in your ~/.bash_profile or ~/.bashrc.
To get the exact same prompt as in your question, change the export PS1 line at the end of .bash_prompt like this:
export PS1="\[${BOLD}${MAGENTA}\]\u\[$WHITE\]#\[$ORANGE\]\h\[$WHITE\]: [\[$GREEN\]\w\[$WHITE\]\$([[ -n \$(git branch 2> /dev/null) ]] && echo \" - \")\[$PURPLE\]\$(parse_git_branch)\[$WHITE\]] \$ \[$RESET\]"
I ended up using all the .bash* files from this repository about a month ago, and it's been really useful for me.
For Git, there are extra goodies in .gitconfig.
And since you're a mac user, there are even more goodies in .osx.
To expand on the existing great answers, a very simple way to get a great looking terminal is to use the open source Dotfiles project.
https://github.com/mathiasbynens/dotfiles
Installation is dead simple on OSX and Linux. Run the following command in Terminal.
git clone https://github.com/mathiasbynens/dotfiles.git && cd dotfiles && source bootstrap.sh
This is going to:
Git clone the repo.
cd into the folder.
Run the installation bash script.
For Mac Catilina 10.15.5 and later version:
add in your ~/.zshrc file
function parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
setopt PROMPT_SUBST
export PROMPT='%F{grey}%n%f %F{cyan}%~%f %F{green}$(parse_git_branch)%f %F{normal}$%f '
My prompt includes:
Exit status of last command (if not 0)
Distinctive changes when root
rsync-style user#host:pathname for copy-paste goodness
Git branch, index, modified, untracked and upstream information
Pretty colours
Example:
To do this, add the following to your ~/.bashrc:
#
# Set the prompt #
#
# Select git info displayed, see /usr/share/git/completion/git-prompt.sh for more
export GIT_PS1_SHOWDIRTYSTATE=1 # '*'=unstaged, '+'=staged
export GIT_PS1_SHOWSTASHSTATE=1 # '$'=stashed
export GIT_PS1_SHOWUNTRACKEDFILES=1 # '%'=untracked
export GIT_PS1_SHOWUPSTREAM="verbose" # 'u='=no difference, 'u+1'=ahead by 1 commit
export GIT_PS1_STATESEPARATOR='' # No space between branch and index status
export GIT_PS1_DESCRIBE_STYLE="describe" # detached HEAD style:
# contains relative to newer annotated tag (v1.6.3.2~35)
# branch relative to newer tag or branch (master~4)
# describe relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
# default exactly eatching tag
# Check if we support colours
__colour_enabled() {
local -i colors=$(tput colors 2>/dev/null)
[[ $? -eq 0 ]] && [[ $colors -gt 2 ]]
}
unset __colourise_prompt && __colour_enabled && __colourise_prompt=1
__set_bash_prompt()
{
local exit="$?" # Save the exit status of the last command
# PS1 is made from $PreGitPS1 + <git-status> + $PostGitPS1
local PreGitPS1="${debian_chroot:+($debian_chroot)}"
local PostGitPS1=""
if [[ $__colourise_prompt ]]; then
export GIT_PS1_SHOWCOLORHINTS=1
# Wrap the colour codes between \[ and \], so that
# bash counts the correct number of characters for line wrapping:
local Red='\[\e[0;31m\]'; local BRed='\[\e[1;31m\]'
local Gre='\[\e[0;32m\]'; local BGre='\[\e[1;32m\]'
local Yel='\[\e[0;33m\]'; local BYel='\[\e[1;33m\]'
local Blu='\[\e[0;34m\]'; local BBlu='\[\e[1;34m\]'
local Mag='\[\e[0;35m\]'; local BMag='\[\e[1;35m\]'
local Cya='\[\e[0;36m\]'; local BCya='\[\e[1;36m\]'
local Whi='\[\e[0;37m\]'; local BWhi='\[\e[1;37m\]'
local None='\[\e[0m\]' # Return to default colour
# No username and bright colour if root
if [[ ${EUID} == 0 ]]; then
PreGitPS1+="$BRed\h "
else
PreGitPS1+="$Red\u#\h$None:"
fi
PreGitPS1+="$Blu\w$None"
else # No colour
# Sets prompt like: ravi#boxy:~/prj/sample_app
unset GIT_PS1_SHOWCOLORHINTS
PreGitPS1="${debian_chroot:+($debian_chroot)}\u#\h:\w"
fi
# Now build the part after git's status
# Highlight non-standard exit codes
if [[ $exit != 0 ]]; then
PostGitPS1="$Red[$exit]"
fi
# Change colour of prompt if root
if [[ ${EUID} == 0 ]]; then
PostGitPS1+="$BRed"'\$ '"$None"
else
PostGitPS1+="$Mag"'\$ '"$None"
fi
# Set PS1 from $PreGitPS1 + <git-status> + $PostGitPS1
__git_ps1 "$PreGitPS1" "$PostGitPS1" '(%s)'
# echo '$PS1='"$PS1" # debug
# defaut Linux Mint 17.2 user prompt:
# PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u#\h\[\033[01;34m\] \w\[\033[00m\] $(__git_ps1 "(%s)") \$ '
}
# This tells bash to reinterpret PS1 after every command, which we
# need because __git_ps1 will return different text and colors
PROMPT_COMMAND=__set_bash_prompt
In 2019, I think git branch --show-current is a better command than the accepted answer.
$ git branch --show-current
master
(Added in git 2.22 release in June 2019)
It runs much faster as it doesn't need to iterate through all branches. Similarly git branch should be avoided too in the command prompt as it slows down your prompt if you have many local branches.
Put it in a function to use anywhere on command prompt:
# This function returns '' in all below cases:
# - git not installed or command not found
# - not in a git repo
# - in a git repo but not on a branch (HEAD detached)
get_git_current_branch() {
git branch --show-current 2> /dev/null
}
More context:
$ git version
git version 2.23.0
Just Install the oh-my-zsh plugins as described in this link.
It works best on macOS and Linux.
Basic Installation
Oh My Zsh is installed by running one of the following commands in your terminal. You can install this via the command-line with either curl or wget.
via curl
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
via wget
sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
for anyone still looking for this , i just installed ohmyz
https://ohmyz.sh/#install and the branches it's showing
In the new Catalina OS for Mac
i) zsh way. Add below lines in .zshrc
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1/'
}
COLOR_DEF='%f'
COLOR_DIR='%F{197}'
COLOR_GIT='%F{33}'
setopt PROMPT_SUBST
export PROMPT='${COLOR_DIR}%1d${COLOR_DEF}${COLOR_GIT}$(parse_git_branch)${COLOR_DEF} $ '
ii) Or to use old bash, you need to change
System Preference -> Users & Groups -> Right click user user
-> Advanced Option -> Login shell -> /bin/bash
Write .bash_profile as below and restart the system
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1/'
}
export PS1="\W\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $ "
Output: FolderName BranchName $
The git package installed on your system includes bash files to aid you in creating an informative prompt. To create colors, you will need to insert terminal escape sequences into your prompt. And, the final ingredient is to update your prompt after each command gets executed by using the built-in variable PROMPT_COMMAND.
Edit your ~/.bashrc to include the following, and you should get the prompt in your question, modulo some color differences.
#
# Git provides a bash file to create an informative prompt. This is its standard
# location on Linux. On Mac, you should be able to find it under your Git
# installation. If you are unable to find the file, I have a copy of it on my GitHub.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-git-prompt.sh
#
source /usr/share/git/completion/git-prompt.sh
#
# Next, we need to define some terminal escape sequences for colors. For a fuller
# list of colors, and an example how to use them, see my bash color file on my GitHub
# and my coniguration for colored man pages.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/10-colors.sh
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-less.sh
#
color_start='\e['
color_end='m'
color_reset='\e[0m'
color_bg_blue='44'
#
# To get a fancy git prompt, it's not sufficient to set PS1. Instead, we set PROMPT_COMMAND,
# a built in Bash variable that gets evaluated before each render of the prompt.
#
export PROMPT_COMMAND="PS1=\"\${color_start}\${color_bg_blue}\${color_end}\u#\h [\w\$(__git_ps1 \" - %s\")]\${color_reset}\n\$ \""
#
# If you find that the working directory that appears in the prompt is ofter too long,
# then trim it.
#
export PROMPT_DIRTRIM=3
There are many PS1 generators but ezprompt has the git status (2nd tab 'Status Elements' ) also.
For macOS:
Step 1:
Create and edit a .zshrc file that will be used for terminal configuration.
touch ~/.zshrc; open ~/.zshrc
Step 2:
Add this to your ~/.zshrc file:
function parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
setopt PROMPT_SUBST
export PROMPT='%F{grey}%n%f %F{cyan}%~%f %F{green}$(parse_git_branch)%f %F{normal}$%f '
Based on 6LYTH3's answer I've decided to post my own due to some improvements that may come in handy:
Simple solution
Open ~/.bash_profile and add the following content
# \[\e[0m\] resets the color to default color
reset_color='\[\e[0m\]'
# \[\033[33m\] sets the color to yellow
path_color='\[\033[33m\]'
# \e[0;32m\ sets the color to green
git_clean_color='\[\e[0;32m\]'
# \e[0;31m\ sets the color to red
git_dirty_color='\[\e[0;31m\]'
# determines if the git branch you are on is clean or dirty
git_prompt ()
{
# Is this a git directory?
if ! git rev-parse --git-dir > /dev/null 2>&1; then
return 0
fi
# Grab working branch name
git_branch=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p')
# Clean or dirty branch
if git diff --quiet 2>/dev/null >&2; then
git_color="${git_clean_color}"
else
git_color="${git_dirty_color}"
fi
echo " [$git_color$git_branch${reset_color}]"
}
export PS1="${path_color}\w\[\e[0m\]$(git_prompt)\n"
This should:
1) Prompt the path you're in, in color: path_color.
2) Tell you which branch are you.
3) Color the name of the branch based on the status of the branch with git_clean_color
for a clean work directory and git_dirty_color for a dirty one.
4) The brackets should stay in the default color you established in your computer.
5) Puts the prompt in the next line for readability.
You can customize the colors with this list
Sophisticated Solution
Another option is to use Git Bash Prompt, install with this. I used the option via Homebrew on Mac OS X.
git_prompt_list_themes to see the themes but I didn't like any of them.
git_prompt_color_samples to see available colors.
git_prompt_make_custom_theme [<Name of base theme>] to create a new custom theme, this should create a .git-prompt-colors.sh file.
subl ~/.git-prompt-colors.sh to open git-prompt-colors.sh and customize:
The .git-prompt-colors.sh file should look like this with my customization
override_git_prompt_colors() {
GIT_PROMPT_THEME_NAME="Custom"
# Clean or dirty branch
if git diff --quiet 2>/dev/null >&2; then
GIT_PROMPT_BRANCH="${Green}"
else
GIT_PROMPT_BRANCH="${Red}"
fi
}
reload_git_prompt_colors "Custom"
Hope this helps, have a great day!
In Catalina and above, you can open your .zshrc file by running nano ~/.zshrc, and posting the following at the top of the document:
# Show git branch in terminal
function parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
COLOR_DEF=$'\e[0m'
COLOR_USR=$'\e[38;5;243m'
COLOR_DIR=$'\e[38;5;220m’
COLOR_GIT=$'\e[38;5;39m'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n ${COLOR_DIR}%~
${COLOR_GIT}$(parse_git_branch)${COLOR_DEF} $ '
Exit and save. Restart your terminal, or run exec zsh and that should be it.
OR
You can check out this theme and see if you like it. It is really easy to install and looks good in my opinion:
https://github.com/romkatv/powerlevel10k#configuration
Hope that helps.
From Mac OS Catalina
.bash_profile is replaced with .zprofile
Step 1:
Create a .zprofile
touch .zprofile
Step 2:
nano .zprofile
type below line in this
source ~/.bash_profile
and save(ctrl+o return ctrl+x)
Step 3:
Restart your terminal
To Add Git Branch Name
Now you can add below lines in .bash_profile
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u#\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "
Restart your terminal this will work.
Note:
Even you can rename .bash_profile to .zprofile that also works.
Keep it fast, keep it simple
put this in your ~/.bashrc file.
git_stuff() {
git_branch=$(git branch --show-current 2> /dev/null)
if [[ $git_branch == "" ]];then
echo -e ""
elif [[ $git_branch == *"Nocommit"* ]];then
echo -e "No commits"
else
echo -e "$git_branch"
fi
}
prompt() {
PS1="\e[2m$(date +%H:%M:%S.%3N) \e[4m$(git_stuff)\033[0m\n\w$ "
}
PROMPT_COMMAND=prompt
Then source ~/.bashrc
Did some searching & then adjusted it a bit & settled with this.
vi ~/.zshrc
And within zshrc file ->
function git_branch_name()
{
branch=$(git symbolic-ref HEAD 2> /dev/null | awk 'BEGIN{FS="/"} {print $NF}')
if [[ $branch == "" ]];
then
:
else
echo '- ('$branch')'
fi
}
setopt prompt_subst
prompt='%n %1/ $(git_branch_name) $ '
through a custom script i update my CFBundleVersion in my app-info.plist when I build and run the app. This information is used as well in the app to display the app name and version. The update works fine in the build process, but the unfortunatly the old information is read in the app itself.
E.g. When I build and run the app the app-info.plist is updated, the CFBundleVersion has now the value 8, but in the simulator the value 7 is shown.
Seems so that the updated app-info.plist is not used in the build process, instead the old version is used.
How can I ensure that the updated app-info.plist is used in my app?
On the one hand somehow the execution of the script should be the first thing in the build-process or on the other hand the app-info.plist should be renewed in the build process. But for both I do not know how to do this...
I added the custom script under Project > Buildphases > Add Build Phase > Add Run Script. With the following contents:
shell: /bin/bash Tools/addVersionNumber.sh
Tools/addVersionNumber.sh -> works like desired
#/bin/bash
# script that should be executed in the build phase
# to set the build number correct
plist="app-folder/app-Info.plist"
## get git information
# git_rev_full_hash=$( git rev-parse HEAD )
git_amount_commits=$( git rev-list HEAD | wc -l )
git_rev_short_hash=$( git rev-parse --short HEAD )
buildRevision="$git_amount_commits: $git_rev_short_hash"
# set build revision ( git short hash - amount of commits )
/usr/libexec/PlistBuddy -c "Set :BuildRevision $buildRevision" $plist""
## build number
buildNumber=$( /usr/libexec/PlistBuddy -c "Print CFBundleVersion" $plist )
buildNumber=$(( $buildNumber + 1 ))
# set new build number
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" $plist
cheers -- jerik
Found a solution. The trick was that the info.plist in the build folder and the plist in dsym (?) has to be updated as well.
My runscript looks now like this
#/bin/bash
# script that should be executed in the build phase
# to set the build number correct
#
# http://www.cimgf.com/2008/04/13/git-and-xcode-a-git-build-number-script/
# http://stackoverflow.com/questions/7944185/how-to-get-xcode-to-add-build-date-time-to-info-plist-file
# http://www.danandcheryl.com/2012/10/automatic-build-numbers-for-ios-apps-using-xcode
# Marketing Number is in CFBundleShortVersionString - will be edited manually
# #TODO add logging
plist="app-folder/app-Info.plist"
build_plist=$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH
conInfo="Contents/Info.plist"
dsym_plist=$DWARF_DSYM_FOLDER_PATH/$DWARF_DSYM_FILE_NAME/$conInfo
function writePlist( ) {
# set build revision ( git short hash - amount of commits )
/usr/libexec/PlistBuddy -c "Set :BuildRevision $buildRevision" $1
# set build date
/usr/libexec/PlistBuddy -c "Set :BuildDate $buildDate" $1
#set build number
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" $1
}
# git_rev_full_hash=$( git rev-parse HEAD )
buildRevision=$( git rev-parse --short HEAD )
git_rev_plist_hash=$( /usr/libexec/PlistBuddy -c "Print BuildRevision" $plist )
# Only update version if a commit was performed. Avoid update version when in development cycle
if [[ $git_rev_plist_hash != $buildRevision ]]; then
### variables for updating plist
# set new build number and date
buildNumber=$( /usr/libexec/PlistBuddy -c "Print CFBundleVersion" $plist )
buildNumber=$(( $buildNumber + 1 ))
buildDate=$(date "+%Y-%m-%d %T %z %Z")
writePlist $plist
writePlist $build_plist
writePlist $dsym_plist
fi
cheers -- jerik
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...