0

I am trying to write a shell program such that it opens a directory and then adds it into a stack.(This is Task 4-8 from book "Learning the bash Shell by Cameron Newham and Bill Rosenblatt")

First, I create a variable in ".profile.sh" as:

export DIR_STACK=""

This allows to initialize the stack when the system log in. Next, I create a file named "pushd.sh" as:

#!/bin/bash 
dirname=$1
DIR_STACK="${dirname:-$PWD}"
cd $dirname

Running this command

>>./pushd.sh directory

should update the DIR_STACK variable and open the directory. But this doesn't work!! I mean when I run

>>echo "$DIR_STACK" 

the output is

>>""

Any hint would be appreciated. (Note that the file "pushd.sh" has been executable by chmod)

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
user51780
  • 139
  • 2
  • 5
  • 2
    Because you're running the script, the DIR_STACK is modified *in a separate process* -- it cannot update the value in your _current, interactive_ shell. – glenn jackman May 18 '22 at 21:44
  • Please take a look at [How do I format my posts using Markdown or HTML?](https://stackoverflow.com/help/formatting). – Cyrus May 18 '22 at 21:48
  • 1
    If you want to modify an interactive shell's state, you should be building a shell function, not an external script. – Charles Duffy May 18 '22 at 22:00
  • BTW, if you want to store a list of filenames, you should be storing it as an array. Because path can contain all possible ASCII characters, including a newline or a `:`, there's no character you can put in your string to specify where one name ends and the next one begins. – Charles Duffy May 18 '22 at 22:01
  • (...if your book is telling you to build a stack before it told you how to use arrays, I strongly suggest throwing it out and finding a different book; likewise, if it's telling you `cd $dirname`, as opposed to `cd "$dirname"`, is acceptable practice). – Charles Duffy May 18 '22 at 22:02
  • The book is one of the most popular one in shell programming. I should mention that the goal here is not not build a perfect stack but rather to demonstrate some basic concepts. – user51780 May 19 '22 at 05:53
  • I dont understand it! because when I run the script using "source" command, it works just fine!! – user51780 May 19 '22 at 06:05

0 Answers0