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

April 20, 2025 2 answers
Asked by mostly-in-working-order-
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!

Answers

umbrella indoors
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!

harbor.57: 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.

Reply to this answer
FOURTH.wall
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!
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions