Terminal (Mac) create alias that includes user input
Asked Answered
G

1

5

In Mac OS Terminal, I'm learning the basics of Unix. I'm having trouble with a hopeful easy fix, but cannot figure out where to start looking.

cd __________ && ls

That is a pretty common pattern for me, to check and see the file folder I'm working in. To save myself keystrokes, I thought to make an alias in my .profile

alias cd='cd && ls'

Now, the obvious flaw (which was not obvious to me) was I would not be able to give it a directory to actually change to

cd ~/Documents/ && ls

This is what I would like to do, but not have to type those last four characters. Any ideas on how I could incorporate my user input (maybe some kind of $(pbpaste) option?

Any help or suggestions would be appreciated.

Gormley answered 15/1, 2014 at 21:16 Comment(0)
L
7

You need to first create BASH function for this instead of alias:

mycd() { cd "$1"; ls; }
alias cd='mycd '

then use it like this:

cd ~/Documents/
Lecythus answered 15/1, 2014 at 21:18 Comment(5)
then you can create an alias of your function :DLapp
+1 good.. For the OP I'll suggest not to overwrite cd command :PLapp
An alterative to the alias is cd () { builtin cd "$1" && ls; }, although @gtgaxiola's suggestion of not overriding the builtin is a good one.Pimiento
Thanks! okay, I'm trying it. It seemed like a bad idea to overwrite cd as I was doing it (trapped me in a folder after sourcing it). This helps!Gormley
most common use of this is find which mac process is using a port , I implemented it writting following in my ~/.bash_profile get_tcp_port() { lsof -i tcp:"$1"; } alias who_is_using="get_tcp_port" and then refresh terminal to use new bash_profile using source ~/.bash_profile , then use it like regular alias in terminal who_is_using 8080Lacreshalacrimal

© 2022 - 2024 — McMap. All rights reserved.