Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stay in directory changed after ending of bash script

Tags:

bash

shell

cd

My bash script:

#!/bin/bash
cd /tmp

Before running my script:

pwd: /

After running my script:

pwd: /

After runnig my script trough sourcing it:

pwd: /tmp

How I can stay at the path from the script without sourcing it ?

like image 603
astropanic Avatar asked Dec 16 '10 14:12

astropanic


People also ask

How do I stop bash from overwriting?

How do I avoid accidental overwriting of a file on bash shell? You can tell bash shell not to delete file data / contents by mistake by setting noclobber variable. It can keep you from accidentally destroying your existing files by redirecting input over an already-existing file.

How do I go back a directory in bash?

You can go back to the parent directory of any current directory by using the command cd .. , as the full path of the current working directory is understood by Bash . You can also go back to your home directory (e.g. /users/jpalomino ) at any time using the command cd ~ (the character known as the tilde).

Do I need exit in Bash script?

The exit command can be written into a Bash script to manually terminate it at a certain point. An exit code of 0 usually indicates that the script exited without any errors. An exit code of 1 or higher usually indicates that an error was encountered upon exit.

What does end do in bash?

End is the way you "call" the text you are about to insert. Once you are done, you indicate the end of the block with the same word in the very beginning of a new line.


2 Answers

You can't. Changes to the current directory only affect the current process.

like image 122
Ignacio Vazquez-Abrams Avatar answered Oct 12 '22 04:10

Ignacio Vazquez-Abrams


Let me elaborate a little bit on this:

When you run the script, bash creates a new process for it, and changes to the current directory only affect that process.

When you source the script, the script is executed directly by the shell you are running, without creating extra processes, so changes to the current directory are visible to your main shell process.

So, as Ignacio pointed out, this can not be done

like image 45
Maxim Sloyko Avatar answered Oct 12 '22 06:10

Maxim Sloyko