Change the current directory from a Bash script
Solution 1:
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.
Instead, you can start your script like this:
. myscript.sh
The .
will evaluate the script in the current environment, so it might be altered
Solution 2:
You need to convert your script to a shell function:
#!/bin/bash
#
# this script should not be run directly,
# instead you need to source it from your .bashrc,
# by adding this line:
# . ~/bin/myprog.sh
#
function myprog() {
A=$1
B=$2
echo "aaa ${A} bbb ${B} ccc"
cd /proc
}
The reason is that each process has its own current directory, and when you execute a program from the shell it is run in a new process. The standard "cd", "pushd" and "popd" are builtin to the shell interpreter so that they affect the shell process.
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.
Solution 3:
In light of the unreadability and overcomplication of answers, i believe this is what the requestor should do
- add that script to the
PATH
- run the script as
. scriptname
The .
(dot) will make sure the script is not run in a child shell.
Solution 4:
Putting the above together, you can make an alias
alias your_cmd=". your_cmd"
if you don't want to write the leading "." each time you want to source your script to the shell environment, or if you simply don't want to remember that must be done for the script to work correctly.
Solution 5:
If you are using bash you can try alias:
into the .bashrc file add this line:
alias p='cd /home/serdar/my_new_folder/path/'
when you write "p" on the command line, it will change the directory.