1

I'm pushing directories to my stack using a while loop that reads the contents of a file. I've tried two approaches that should be equivalent, but they behave different.

Approach 1

export DIRSTACK_SAVEFILE="/path/to/file" # file contains full paths to folders in each line while read line ; do pushd -n "$line" done < <(tac $DIRSTACK_SAVEFILE) 

Using this, I can later use dir and pushd +n and all the folders are loaded into the stack.

Approach 2

export DIRSTACK_SAVEFILE="/path/to/file" # file contains full paths to folders in each line tac $DIRSTACK_SAVEFILE | while read line ; do pushd -n "$line" done 

After executing this approach, the directory stack in my shell has no new folders.

Question

Why only the 1st approach changes the directory stack in my shell?

I've searched to understand how process substitution and pipe work. I think I understand what I read here about process substitution but I haven't found any explanation about pipe that helps me understand this behavior.

PD.: I'm using GNU bash, version 5.1.8(1)-release (x86_64-redhat-linux-gnu)

0

1 Answer 1

3

As documented in man bash under Pipelines:

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

Therefore, the changes to the current working directory happen in a subshell which doesn't influence the current working directory of the parent shell.

You can run the last element of a pipeline in the current shell by setting

shopt -s lastpipe 

In this case, it should make the second approach work, as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.