-1

I figured out that very often I use both the cd and ls commands one after the other. This is when I decided to create a bash function for it.

The code that I inserted into the bashrc file is this:

function cs () {
  cd "$@" && ls;
}

The problem that I have is that the output of "ls" is good but I do not really navigate to that directory.

For example, when I call "cs Downloads/" I get as an output the content of Downloads but I do not navigate inside it.

I am new to the bash and I am sorry if I do any noob mistake.

  • 2
    Hint: You probably don't really want to use `$@` as parameters for `cd`; replace it by `$1`. – Murphy Mar 11 '16 at 14:22
  • 1
    How are you running this command? Run as `cs ` in, say, your interactive shell should work just fine. If you run `contents=$(cs )` to get the contents in a variable (which you **should not** do since [parsing `ls`](http://mywiki.wooledge.org/ParsingLs) is a bad idea) then it won't work for the reasons the two answerers gave, you are running it in a sub-shell so it can't affect the current shell. – Etan Reisner Mar 11 '16 at 14:24

1 Answers1

1

The function works well for me when dropped into ~/.bashrc and not called with more than one parameter. Here's a cleaned-up version that addresses minor issues:

function cs() {
  cd "$1" && ls
}

If you still have problems with that then please provide more details in your question: How you call it, what's the exact output, and what you expected instead.

Murphy
  • 3,827
  • 4
  • 21
  • 35
  • I call it like this "cs Downloads/" and what I get is the content of that directory but I do not navigate inside it. – Stefan Idriceanu Mar 11 '16 at 15:25
  • @StefanIdriceanu That's exactly what works for me when called from console. Do you call it from the console or from inside a script? Do you have an `alias` defined for `cs` or `ls`? Does the content of `cs` look as expected when you print it with `set`? If possible please provide the literal (anonymized) console output containing the relevant lines in your question instead of a description what you see, else this is getting nowhere. – Murphy Mar 11 '16 at 15:42
  • I got it fixed, apparently I was having some alias with the same name as my function and was running that one instead of my function. – Stefan Idriceanu Mar 11 '16 at 16:02