I\'m trying to write a small script to change the current directory to my project directory:
#!/bin/bash
cd /home/tree/projects/java
I save
In your ~/.bash_profile file. add the next function
move_me() {
cd ~/path/to/dest
}
Restart terminal and you can type
move_me
and you will be moved to the destination folder.
You can combine an alias and a script,
alias proj="cd \`/usr/bin/proj !*\`"
provided that the script echos the destination path. Note that those are backticks surrounding the script name.
For example, your script could be
#!/bin/bash
echo /home/askgelal/projects/java/$1
The advantage with this technique is that the script could take any number of command line parameters and emit different destinations calculated by possibly complex logic.
You can create a function like below in your .bash_profile
and it will work smoothly.
The following function takes an optional parameter which is a project. For example, you can just run
cdproj
or
cdproj project_name
Here is the function definition.
cdproj(){
dir=/Users/yourname/projects
if [ "$1" ]; then
cd "${dir}/${1}"
else
cd "${dir}"
fi
}
Dont forget to source your .bash_profile
You can use .
to execute a script in the current shell environment:
. script_name
or alternatively, its more readable but shell specific alias source
:
source script_name
This avoids the subshell, and allows any variables or builtins (including cd
) to affect the current shell instead.
You need no script, only set the correct option and create an environment variable.
shopt -s cdable_vars
in your ~/.bashrc
allows to cd
to the content of environment variables.
Create such an environment variable:
export myjava="/home/tree/projects/java"
and you can use:
cd myjava
Other alternatives.
The cd
in your script technically worked as it changed the directory of the shell that ran the script, but that was a separate process forked from your interactive shell.
A Posix-compatible way to solve this problem is to define a shell procedure rather than a shell-invoked command script.
jhome () {
cd /home/tree/projects/java
}
You can just type this in or put it in one of the various shell startup files.