Why doesn't “cd” work in a shell script?

2018-12-31 01:44发布

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 saved this file as proj, added execute permission with chmod, and copied it to /usr/bin. When I call it by: proj, it does nothing. What am I doing wrong?

标签: linux shell
29条回答
君临天下
2楼-- · 2018-12-31 02:28

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.

查看更多
柔情千种
3楼-- · 2018-12-31 02:29

You can use the operator && :

cd myDirectory && ls

查看更多
浮光初槿花落
4楼-- · 2018-12-31 02:32

To make a bash script that will cd to a select directory :

Create the script file

#!/bin/sh
# file : /scripts/cdjava
#
cd /home/askgelal/projects/java

Then create an alias in your startup file.

#!/bin/sh
# file /scripts/mastercode.sh
#
alias cdjava='. /scripts/cdjava'

  • I created a startup file where I dump all my aliases and custom functions.
  • Then I source this file into my .bashrc to have it set on each boot.

For example, create a master aliases/functions file: /scripts/mastercode.sh
(Put the alias in this file.)

Then at the end of your .bashrc file:

source /scripts/mastercode.sh



Now its easy to cd to your java directory, just type cdjava and you are there.

查看更多
与风俱净
5楼-- · 2018-12-31 02:32

Jeremy Ruten's idea of using a symlink triggered a thought that hasn't crossed any other answer. Use:

CDPATH=:$HOME/projects

The leading colon is important; it means that if there is a directory 'dir' in the current directory, then 'cd dir' will change to that, rather than hopping off somewhere else. With the value set as shown, you can do:

cd java

and, if there is no sub-directory called java in the current directory, then it will take you directly to $HOME/projects/java - no aliases, no scripts, no dubious execs or dot commands.

My $HOME is /Users/jleffler; my $CDPATH is:

:/Users/jleffler:/Users/jleffler/mail:/Users/jleffler/src:/Users/jleffler/src/perl:/Users/jleffler/src/sqltools:/Users/jleffler/lib:/Users/jleffler/doc:/Users/jleffler/work
查看更多
柔情千种
6楼-- · 2018-12-31 02:34

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.

查看更多
登录 后发表回答