1

I'd like to write a bash scipt that would change to target directory and list the contents of new directory, all in one step. It would replace the two commands I constantly use consecutively:

  • cd ./some_directory
  • ls -al

After executing the script, my current directory would change, and ls -al would show the dir list.

cdl ./some_directory

Is this possible?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Danijel
  • 188

2 Answers2

4

You can’t do this with a shell script, because scripts run in new shells and exiting the script exits the shell and “forgets” the directory change. See Script to change current directory (cd, pwd) for example (there are probably more detailed answers on the site somewhere).

You need to use a function instead:

cd1() {
    cd "$@"
    ls -al
}
Stephen Kitt
  • 434,908
1

Another option (in your .bashrc):

PROMPT_COMMAND='if [[ "$PWD" != "$_promptPWD" ]]; then ls -al; _promptPWD=$PWD; fi'
_promptPWD=$PWD

That hooks into bash's PROMPT_COMMAND functionality to have it run the ls for you, if you've changed directories. The downsides are:

  • would need to be patched into any existing PROMPT_COMMAND, if any
  • clutters the environment with another variable (_promptPWD)

The up-side is that you can continue to type cd as normal, and not need to type something different to get the ls behavior.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255