Reza
Reza

Reputation: 203

alias - cd followed by ls

How can I define an alias so that when I do cd Abcd, where 'Abcd' is the name of a directory, the directory is changed to 'Abcd' and is followed by ls to show the contents of the directory?

Upvotes: 5

Views: 2021

Answers (2)

PCM
PCM

Reputation: 873

UNIX

Creating an alias

Your Linux distribution will most likely not have the .bash_aliases file created in your home, or you can even create it manually. To create the file, type in the following command: touch ~/.bash_alisaes

Now that file will be executed automatically every time you fire off a new Terminal.

What you can do now is create a list of aliases and add them to that file for later uses. create an alias and update the ~/.bash_aliases file to make it permanent.

Generic approach: Creating a custom script

Create a bash script in your /usr/bin folder, it should look something like this

#!/bin/bash
Whatever combination of commands you want to run when you type this thing.

Its really that easy.

Just name the bash script what you want to type in to the terminal, and make it excecutable: chmod +x filename and you're good to go!

WINDOWS

You can use DOSKEY command:

From Wikipedia:

DOSKey is a utility for MS-DOS and Microsoft Windows that adds command history, macro functionality, and improved editing features to the command line interpretersCOMMAND.COM and cmd.exe. It was included as a TSR program with MS-DOS and PC-DOS versions 5 and later, and with Microsoft's Windows 95/98/Me.

For example: To create a macro that quickly and unconditionally formats a disk, type:

doskey qf=format $1 /q /u

To quickly and unconditionally format a disk in drive Z, type:

qf Z:

To define a macro with multiple commands, use $t to separate commands, so the solution to your problem follows:

doskey cd=cd $1$tdir

Now, this will work only in your currently open command window. To make it permanent simply create a batch file and set the value of the absolute path of the file to the regedit

HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun

Source for the regedit: superuser.com/a/238858

Upvotes: -1

Garrett
Garrett

Reputation: 4414

I believe you can't use an alias to accomplish that, but you could define a function to do it:

#print contents after moving to given directory
cl()
{
    cd $@
    ls
}

You could stick this in your ~/.bashrc file.

If you were hoping to override the builtin cd command, then you could do:

#print contents after moving to given directory
cd()
{
    builtin cd $@
    ls
}

Upvotes: 7

Related Questions