Help with bash scripting

I originally asked this in Destination Linux forums, and the answer didn't work for me so I'm going to ask here!

So, I found a video talking about a neat little thing you can do to get better 'examples' for command line commands...

Cheat.sh

The concept was, if you wanted some examples of grep that were easier examples than diving through a man page, you could use curl and at the command line, type curl https://cheat.sh/grep and in the blink of an eye, you would get

# grep
# Matches patterns in input text.
# Supports simple patterns and regular expressions.

# Search for an exact string:
grep search_string path/to/file

# Search in case-insensitive mode:
grep -i search_string path/to/file

# Search recursively (ignoring non-text files) in current directory for an exact string:
grep -RI search_string .

# Use extended regular expressions (supporting `?`, `+`, `{}`, `()` and `|`):
grep -E ^regex$ path/to/file

# Print 3 lines of [C]ontext around, [B]efore, or [A]fter each match:
grep -C|B|A 3 search_string path/to/file

# Print file name with the corresponding line number for each match:
grep -Hn search_string path/to/file

# Use the standard input instead of a file:
cat path/to/file | grep search_string

# Invert match for excluding specific strings:
grep -v search_string

which is very useful!!

So, what I wanted to do was create an alias so I could just type cheat grep and get the same results...

However, that won't work because of the space (it would send curl https://cheat.sh/ grep) which results in the cheat.sh main page and then curl: (6) Could not resolve host: grep because of the space...

So I tried to make a bash function...

function cheat { curl https://cheat.sh/$1 }

which gives me the same error...

So how can I create a function/alias for this to work... and if it's a bash function, where should I put it (it's own file or a custom 'bash scripts' file that has more than this), and where can I link it so that it always runs when I type cheat from the command line (I was originally thinking bash rc - but then just like it's better to put custom aliases in their own file, I figured I should put custom small functions in their own file as well)

Sorry for rambling!

I added at the bottom of my .bashrc

function cheat() {
  /usr/bin/curl https://cheat.sh/$1
}

started new terminal, cheat lsof, it gives examples how to use lsof

2 Likes