Skip to content

Instantly share code, notes, and snippets.

@HarshitJoshi9152
Created October 6, 2021 21:08
Show Gist options
  • Save HarshitJoshi9152/ec59db1fbddbbb8fb658158edbc95fd7 to your computer and use it in GitHub Desktop.
Save HarshitJoshi9152/ec59db1fbddbbb8fb658158edbc95fd7 to your computer and use it in GitHub Desktop.
Simple one liner to cheat elegently | cheat.sh aliasing
curl "http://cheat.sh/$*"
# doesnt work if you use $@ instead of $*
# because $* doesnt preserve spaces while $@ does
# https://www.shellscript.sh/variables2.html
# The first set of variables we will look at are $0 .. $9 and $#.
# The variable $0 is the basename of the program as it was called.
# $1 .. $9 are the first 9 additional parameters the script was called with.
# The variable $@ is all parameters $1 .. whatever. The variable $*, is similar,
# but does not preserve any whitespace, and quoting, so "File with spaces" becomes "File" "with" "spaces". This is similar to the echo stuff we looked at in A First Script. As a general rule, use $@ and avoid $*.
# $# is the number of parameters the script was called with.
# Let's take an example script:
@HarshitJoshi9152
Copy link
Author

cheat

@HarshitJoshi9152
Copy link
Author

HarshitJoshi9152 commented Oct 22, 2021

edit: -l flag added to see output in less

# cheat.sh wrapper

# refer to this for better args handling
#https://superuser.com/questions/186272/check-if-any-of-the-parameters-to-a-bash-script-match-a-string/186279#186279
_less=false
cheat_argv=""
for i in "$@"; do
	if [ "$i" == "-l" ]; then
		_less=true
		continue
	fi
	# to avoid bad cheat.sh request url path because of whitespace.
	if [ "$cheat_argv" = "" ]; then
		cheat_argv="$i"
	else
		cheat_argv="$cheat_argv $i"
	fi
done

if [ "$_less" = true ]; then
	curl "http://cheat.sh/$cheat_argv" | less -R
else
    curl "http://cheat.sh/$*"
fi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment