Search code examples
bashoutput-redirect

Use output redirection to change directory


I was working with BASH and used output redirection to save a directory path to a file. When I try to re-use the input stored in the file using input redirection it doesn't work.

I wrote 2 functions, one which redirects the output and the other which redirects input to the cd command.

#!/bin/bash



savepath () {


pwd > /home/user/Documents/save_path.txt

}

gotopath () {


cd < /home/user/Documents/save_path.txt

}

Save the shell script and made it executable. I then used source to enable myself to call my functions inside the shell.

After running the first savepath() and changing to any random directory, running the second function should send me back to the directory I ran savepath() from. It isn't doing that, instead it sends me to my home directory.


Solution

  • Try this:

    #!/bin/bash
    
    SAVEPATH=$HOME/Documents/save_path.txt
    
    savepath () {
        pwd > $SAVEPATH
    }
    
    gotopath () {
        cd `cat $SAVEPATH`
    }
    

    The original implementation tried to pass the saved path via stdin. This is not the way that cd works: it needs the target directory as an argument. Using this approach the content of the file is substituted as an argument.

    enter image description here