cd works in shell but not in script

5,701

Solution 1

just doing

./cdscript

won't work. basically you forked a new shell, in which you cd, then the shell (and new working dir) exit.

You need to use

. ./cdscript

(there is a leading dot, and a space)

The first dot means : run ./cdscript as if I typed it. The second dot is needed if . is not in your PATH var.

Solution 2

The script changes your current working directory but then it is restored upon exit. Instead of typing

cdscript 

try typing

 . cdscript

to run your script for the desired result.

Share:
5,701

Related videos on Youtube

Escher
Author by

Escher

Updated on September 18, 2022

Comments

  • Escher
    Escher almost 2 years

    I frequently have to cd from $HOME to a particular long directory path. So I thought I'd put a cdscript in $HOME to make getting there a little quicker.

    cdscript:

    #!/bin/sh
    directory="/some/big/long directory path/that/I/use/frequently"
    cd "$directory"
    

    Set permissions: chmod 700 cdscript

    ./cdscript doesn't do anything. What am I missing? (Yes, those spaces in the path exist, and I can copy and paste the exact individual lines in the shell with success, so the path exists too). Also, is it more Unixey to just make a symbolic link to the directory instead of the above script, and cd to the link instead?