How to Create a Working Alias for a Command with Arguments?

0
0
Asked By CuriousCoder42 On

Hey everyone! I'm trying to set up an alias that incorporates the word 'cheat.' For example, I'd love to type something like 'cheat [topic]' and have it execute a command. I attempted the following alias: `alias cheat="curl cht.sh/$1"`, but it doesn't seem to work as I expected. I think the issue might be due to the whitespace between the command and its argument. Can anyone help me figure out how to get this alias working? When I type 'cheat zip', I want the command to become 'curl cht.sh.zip'. Thanks in advance for your help!

2 Answers

Answered By CodeMaster88 On

Just to clarify the alias vs. function topic: aliases are still valid in bash. They’re meant for simpler tasks, while functions can handle complexity and pass parameters. So, while some may prefer functions, aliases are very much alive and can still be handy for shortening commands. Just keep in mind their limitations in terms of argument handling compared to functions!

Answered By TechieTom On

Here's a straightforward way to create the alias using a function instead. You can add this to your .bashrc:

```bash
cheat (){
curl "https://cheat.sh/$1"
}
```
Also, if you're set on using an alias, you might want to play around with this example:
```bash
set -- 'abc'
alias my_alias='echo "$1"'
my_alias 123
```
This setup shows that parameters for aliases aren’t passed like they are in functions, which is why you're running into trouble. The $1 in an alias refers to the positional parameter of the shell, not the alias itself. Hope that clears things up!

HelpfulHarry -

Thanks for sharing! Quick question: I noticed you're using cheat.sh - what's your reason for that over cht.sh? They both seem to give similar results.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.