fronthem
fronthem

Reputation: 4139

Enter to unix shell with specific working directory

I want to accomplish this:

[zsh]$ pwd
/home/user
*[zsh]$ bash # enter to a bash shell at the same time as `cd ~/Desktop`.
[bash]$ pwd
/home/user/Desktop
[bash]$ exit
[zsh]$ pwd
**/home/user

I would like to know if there is any way to enter to the unix shell at the same time as changing a directory to some specific path. It's important that:

  1. Line * is supposed to be a single-line command for entering a shell and changing a directory,
  2. After exist from any new shell, it's expected to return to the latest location as it was before entering to the shell, see line **.

Upvotes: 0

Views: 447

Answers (5)

rsm
rsm

Reputation: 2560

You can use pushd and popd commands:

pushd ~/Desktop && bash ; popd

pushd in this case is like "remember and cd" - it adds new directory to the top of directory stack, making it current directory. Next you start bash and after you exit bash, popd takes you back to the directory remembered by pushd.

EDIT: changed && to ; for better error handling, as pointed out in comment.

Upvotes: 0

fronthem
fronthem

Reputation: 4139

I think answer of @hchbaw is a bit tricky. I've just found a more effective solution from run bash command in new shell and stay in new shell after this command executes. In my case I can use:

bash --rcfile <(echo "cd ~/Desktop")

Upvotes: 0

hchbaw
hchbaw

Reputation: 5309

Using subshells is also useful for changing the current working directory temporary:

% (cd ~/Desktop && bash)

Upvotes: 2

Kaushik Nayak
Kaushik Nayak

Reputation: 31648

Simply do this.

cd /home/user/Desktop && bash

This will try to change your current directory to /home/user/Desktop and if it succeeds changes the shell to bash else throws error.

Upvotes: 0

user8246956
user8246956

Reputation:

One straightforward answer consists in using a bash configuration file switching to the proper directory. By creating a file ~/.my_bashrc containing a single line:

cd ~/Desktop

you can then just type:

bash --rcfile ~/.my_bashrc

in a terminal to open a new shell directly in the Desktop directory.

Of course you can add other commands in ~/.my_bashrc (aliases, etc.), like in any regular bashrc file.

Upvotes: 0

Related Questions