Hi Can anyone help me with this. Im new to doing scripts. Thanks

I am writing a simple script to cd to another directory. But the directory does not change after running the script. How can i make the directory change after running the script?

operator@tiger013s% pwd

/export/home/tiger013s/operator

operator@tiger013s% more sample

#!/bin/csh

cd /home/local_summary

operator@tiger013s% sample

operator@tiger013s% pwd

/export/home/tiger013s/operator -> i want to be in /home/local_summary

Dani AI

Generated

Short answer: the script runs in a child shell so its cd affects only that process. correctly pointed out the subshell behaviour but removing the shebang is not the right fix — the shebang only chooses the interpreter when you execute the file. is right about running the commands in your current shell; do that instead.

If your interactive shell is csh/tcsh (a % prompt is a clue), run the script in the current shell with the csh source built-in. For bourne-style shells use the POSIX . or bash/zsh source. Example:

# csh/tcsh
source scriptname

# POSIX sh / bash / ksh
. scriptname
# or in bash/zsh
source scriptname

If you prefer to keep running the script as a separate program, have it print the desired path and then change directory from the parent shell via command substitution:

# the script prints the path (no cd inside)
printf '%s\n' /path/to/dir

# in your interactive shell
cd "$(./script-that-prints-path)"

Extra tips: keep the shebang if others will execute the file directly; make the file executable with chmod +x when needed. Be careful when sourcing files you didn’t write—exit or other commands in a sourced file will affect your current shell. If you want every login to start in a particular directory, put a cd in the appropriate startup file (for csh: ~/.login or ~/.cshrc, for bash: ~/.bash_profile / ~/.bashrc).

Recommended Answers

All 2 Replies

Hi,

Remove "#!/bin/csh" from your script. This instructs the shell to begin a new shell session to execute your script. This is why it does not change your 'current' directory. It is the 'new' shell session which changes directory and then that session exits when the script is done.

Kate

And. You have to source the script. It may or may not run in a subshell (another process) with

[b].[/b] myfscript.sh

note the leading dot - in linux there is the source command in bash which does the same thing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.