bash snippets

Git: "fatal: protocol error: bad line length character:"

Tagged git, bash  Languages bash

Git might give you this fine error

fatal: protocol error: bad line length character:

Looks like git didn't receive the response it expected from your server.

Possible causes: * Did you put some echo commands in e.g. ~/.bashrc on the remote server?

How to color your bash prompt red in production

Tagged bash, color, red  Languages bash

How to color your bash prompt red in production:

export RED="\[\e[1;31m\]"
export NORMAL="\[\e[0m\]"

# [email protected]: ~/directory $
BASE_PROMPT="$RED\[email protected]\h$NORMAL: \w "

# Root prompt should have #
if [[ $EUID == 0 ]] ; then
  export PS1="$BASE_PROMPT#"
else
  export PS1="$BASE_PROMPT\$"
fi

Put it in /etc/profile.d/promptcolor.sh for all users to see the prompt in color.

Script also helps with lowering anxiety levels.

"What's my IP" bash script

Tagged bash, wanip, ip, dns  Languages bash

This bash alias displays your IP address:

alias wanip='dig +short myip.opendns.com @resolver1.opendns.com'

How to get the latest version number from a list of git tags

Tagged bash, git, version, zsh  Languages bash

This will print the latest version number that a git repository has been tagged with:

$ git tag -l 'v*' | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n | tail -n 1
v1.5.6

Note that some versions of the sort command have a —version-sort switch, and some don’t:

sort: unrecognized option `--version-sort'
Try `sort --help' for more information.

How to start a bash shell in Docker

Tagged bash, docker, shell  Languages bash

To start a bash shell in an already running container:

docker exec -it <container id/name> bash

To start a bash shell using an image of a container that is not running:

docker run -i -t --entrypoint /bin/bash <image id>

Search and replace file contents and file names

Tagged bash, find, replace, search, zsh  Languages bash

Search and replace file contents

# Replace Tree with Trees
# NOTE: If you want to backup the files, change -i '' to -i (without empty string)
grep -rl Tree . |xargs sed -i '' -e 's/Tree/Trees/'

Search and replace of file names

find . -name '*observation*' -exec bash -c 'mv $0 ${0/observation/condition}' {} \;

References https://www.commandlinefu.com/commands/matching/search-replace/c2VhcmNoIHJlcGxhY2U=/sort-by-votes

How to extract numbers from a string in Bash scripts

Tagged bash, extract, number, regexp, rematch  Languages bash

To extract numbers from a string in Bash scripts you can use a bash feature called REMATCH. You don’t need grep, sed, or awk.

Add this to script.sh (remember to run chmod +x script.sh):

#!/usr/bin/env bash
string="COPY 23845\n3409"
if [[ $string =~ ^COPY[[:space:]]([0-9]+) ]]; then
  echo "Match: ${BASH_REMATCH[1]}"
else
  echo "No match"
fi

This will print 23845, but not 3409. Note that this example uses a capture group.