Last active
March 21, 2022 08:59
-
-
Save MiguelMJ/b56f58d490826cddf8243672e6248aee to your computer and use it in GitHub Desktop.
WS - Fast navigation in Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Source this file from .bashrc | |
# or copy the code inside it | |
ws(){ | |
print_help(){ | |
echo "usage: ws [-s] [options]" | |
echo "" | |
echo "options:" | |
echo " -h print this help message" | |
echo " -s change workspace or apply certain operations to workspaces" | |
echo " -a add current directory to active workspace" | |
echo " -r ID remove item (accepts -s)" | |
echo " -l list items (accepts -s)" | |
echo "" | |
echo "examples:" | |
echo " ws -s my_workspace # create a new workspace" | |
echo " ws -a # add current directory to workspace" | |
echo " ws -l # see directories in workspace" | |
echo " ws -s -l # see created workspaces " | |
echo " ws -r 1 # remove a directory from workspace" | |
echo " ws -s -r my_workspace # remove a workspace" | |
} | |
if [[ $# == 0 ]]; then | |
print_help | |
kill -INT $$ | |
fi | |
# Directory in home | |
wsdir="$HOME/.ws" | |
mkdir -p "$wsdir" | |
# Current workspace directories | |
currwsfile="$wsdir/.$(basename $(tty))" | |
touch "$currwsfile" | |
currws=$(cat "$currwsfile") | |
if [ -z "$currws" ]; then | |
currws="default" | |
fi | |
touch "$wsdir/$currws" | |
# Read options | |
use_superws=0 # Operate on whole workspaces | |
while [ "${1:0:1}" == "-" ]; do | |
case $1 in | |
-h) # Help | |
print_help | |
kill -INT $$ | |
;; | |
-s) # Operate directly on workspaces / change of workspace | |
use_superws=1 | |
if [ "${2:0:1}" != "-" ]; then | |
currws="$2" | |
echo "$currws" > "$currwsfile" | |
shift | |
fi | |
;; | |
-a) # Add | |
if [[ ! -z "$2" ]]; then | |
currws="$2" | |
echo "$currws" > "$currwsfile" | |
shift | |
fi | |
echo $PWD >> "$wsdir/$currws" | |
;; | |
-r) # Remove item | |
if [[ -z "$2" ]]; then | |
echo "Argument missing" | |
fi | |
if [[ $use_superws == 1 ]]; then | |
rm "$wsdir/$2" | |
if [[ "$2" == "$currws" ]]; then | |
currws="default" | |
echo "$currws" > "$currwsfile" | |
fi | |
else | |
sed -i -e "$2d" "$wsdir/$currws" | |
fi | |
shift | |
;; | |
-l) # List items | |
if [[ $use_superws == 1 ]]; then | |
echo "Workspaces:" | |
for i in $wsdir/*;do | |
name="$(basename $i)" | |
if [[ "$name" == "$currws" ]]; then | |
echo "> $name" | |
else | |
echo "- $name" | |
fi | |
done | |
else | |
echo "Workspace $currws:" | |
awk '{print " ",NR, $0}' "$wsdir/$currws" | |
fi | |
;; | |
esac | |
shift | |
done | |
# Move to selected directory | |
if [ ! -z "$1" ]; then | |
dest="$(awk "NR==$1" "$wsdir/$currws")" | |
echo $dest | |
cd "$dest" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment