-1

Trying to set up a shortcut that will allow me to cd into a directory and list the files within in one go

here is what I got so far. My knowledge is limited, this is pretty much just copy and paste from sources online, don't know what I'm doing, but learning in the process:

cdl () {
    cd $1
    ls . $1
}

it does what I want, but produces an error:

ls: cannot access colorschemes/: No such file or directory
.:

how do I get rid of the error message?

m147
  • 29
  • 4
  • 4
    Hint: When you `cd` into a directory called `dirname` does `ls dirname` still make sense? – tadman Aug 10 '17 at 17:44
  • if I take out the `.` from the 3rd line then I get this error 'ls: cannot access colorschemes/: No such file or directory' and doesn't list the files at all – m147 Aug 10 '17 at 17:50

1 Answers1

2

If you already CD to a directory, then there is no need to run nothing more than ls -lth. Its not necessary to mention the directory name again.

function cdl () {
   cd "$1"
   ls -lth
}

I recommend puttin this into your .bash_profile, if you are not already doing it.

Regards!

Matias Barrios
  • 3,700
  • 2
  • 12
  • 33
  • Should really quote `"$1"`. – Benjamin W. Aug 10 '17 at 17:56
  • nice one. thank you. does exactly what I want (minus the -lth flags). can you explain why this works and mine didn't? has it got something to do with the `function` before `cdl`? – m147 Aug 10 '17 at 17:59
  • @m147 Cool. Happy to hear that. – Matias Barrios Aug 10 '17 at 18:00
  • can you explain why this works and mine didn't? has it got something to do with the function before cdl? – m147 Aug 10 '17 at 18:06
  • @m147 You tried to list both `colorschemes/` and `colorschemes/colorschemes/`. The latter is an invalid directory, resulting in the error. It's not related to your function in any way. You will get the same error if you open a terminal, run `cd /` and then `cd tmp` to change to `/tmp` followed by `ls tmp` to try to list a directory `tmp` inside `/tmp`. The correct way to list the current directory is `ls` or `ls .`, not `ls relativeNameOfCurrentDir` – that other guy Aug 10 '17 at 18:06
  • @thatotherguy does that have to do with the `.` or the `$1`? – m147 Aug 10 '17 at 18:10
  • @m147 That has to do with the `$1`. – that other guy Aug 10 '17 at 18:11
  • @thatotherguy nice one! I tried it out in the .bash* files and it works. thanks. still don't quite understand how it all works but I'll figure it out. anyway, I got all this from this site, https://www.digitalocean.com/community/tutorials/an-introduction-to-useful-bash-aliases-and-function. which does include the `$1` on the last line. also, why quote the initial `$1` in the 2nd line in the above example? – m147 Aug 10 '17 at 18:18