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?

  • Not with a script, because script runs in a subshell, and its changes in the current directory aren't reflected in the parent process. You can declare a function, though. – choroba Mar 14 '17 at 10:14
  • 1
    So what's wrong with ls -al ./some_directory? – frostschutz Mar 14 '17 at 10:22
  • I want to cd into directory, and then ls -al. – Danijel Mar 14 '17 at 10:55
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
}
  • Thanks. Where do I put function to? .bash_profile? – Danijel Mar 14 '17 at 10:19
  • 1
    .bashrc would be more appropriate. – Stephen Kitt Mar 14 '17 at 10:22
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.