Can I change directory in a bash script?

Can I change directory in a bash script?

The script is run in a subshell, and cannot change the parent shell working directory. Its effects are lost when it finishes. To change the current shell’s directory permanently you should use the source command, also aliased simply as . , which runs a script in the current shell environment instead of a sub shell.

Can you use cd in shell script?

Trying to use cd inside the shell script does not work because the shell script runs in the subshell and once the script is over it returns to the parent shell, which is why the current directory does not change. To achieve changing of the directory use sourcing. You can either use .

How to change the Directory of the shell?

To change the current shell’s directory permanently you should use the sourcecommand, also aliased simply as., which runs a script in the current shell environment instead of a sub shell. The following commands are identical:

How to change the current directory from a bash script?

Maybe there’s a better way: because while it appears to work, after you run it and your script finishes, yes you’ll be in the correct directory, but you’ll be in it in a subshell, which you can confirm by pressing Ctrl+D afterwards, and you’ll see it exits the subshell, putting you back in your original directory.

How does a script change the environment in Bash?

By making your program a shell function, you are adding your own in-process command and then any directory change gets reflected in the shell process. When you start your script, a new process is created that only inherits your environment. When it ends, it ends. Your current environment stays as it is.

How to run a script to change the current PWD?

I want to run a script to simply change the current working directory: #!/bin/bash cd web/www/project But, after I run it, the current pwd remains unchanged! How can I do that? Stack Exchange Network