0

i want to have an alias "t" to enter a folder and list the content there.

i tried with:

alias t="cd $1; ls -la"

but it just listed the folder i typed but did not enter it. i wonder why?

cause when i use this one:

alias b="cd ..; ls"

it went back to the parent and listed the content.

so i want the "t" do enter the folder i type in too.

someone knows how to do this right?

4 Answers 4

4

You can't pass arguments into bash aliases. You'll need to create a shell function like so:

function t { cd "$1" && ls -la; }

Edit: whoops, forgot the function and edited per Juliano's suggestion.

Sign up to request clarification or add additional context in comments.

2 Comments

function t or t() at the beginning.
I suggest replacing ; with &&. It doesn't make a lot of sense to run ls if the user mistypes the directory name.
2

I don't think you can use aliases that way. You can, however, declare a function:

function t {
    cd "$1"
    ls -la
}

Comments

1

cd is tricky in bash. The command you issued ran in a separate process than your bash shell, and that process terminated when it was done. See Why doesn't "cd" work in a bash shell script?

2 Comments

Nope, that's not the reason in this case.
The cd command (chdir) cannot be implemented as an external. It must be a shell built-in in order to be useful. (That's because it changes the shell's own process state). For similar reasons the read and export and set commands must also built-ins.
1

In most UNIX shells (csh, bash, zsh) aliases are a form of expansion. Thus they are not parsed like functions. Any word in the interactive input stream which would be processed as a command will be scanned against the list of aliases and a simple string replacement will be performed (usually before any other forms of expansion).

If you need to process arguments then you want to define a function which is parsed and processed rather than simply being expanded like a macro.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.