Find the answer to your Linux question:
Results 1 to 3 of 3
i wrote a linux shell program under the bash shell i want to change the user current working directory. the problem is that the $PWD was changed ,but the prompt ...
  1. #1
    Just Joined!
    Join Date
    Sep 2008
    Posts
    2

    a simple linux shell problem

    i wrote a linux shell program under the bash shell

    i want to change the user current working directory.

    the problem is that the $PWD was changed ,but the prompt can not be changed.

    for example:
    #!/bin/bash

    echo $PWD
    cd /mnt/myshell
    echo $PWD

    my current working directory is /root

    the running result of the program is following:
    /root
    /mnt/myshell

    but the prompt is /root still.
    why ???
    some body help me . thanks

  2. #2
    Linux Guru
    Join Date
    Nov 2007
    Location
    Córdoba (Spain)
    Posts
    1,513
    Quote Originally Posted by yang3220 View Post
    i wrote a linux shell program under the bash shell

    i want to change the user current working directory.

    the problem is that the $PWD was changed ,but the prompt can not be changed.

    for example:
    #!/bin/bash

    echo $PWD
    cd /mnt/myshell
    echo $PWD

    my current working directory is /root

    the running result of the program is following:
    /root
    /mnt/myshell

    but the prompt is /root still.
    why ???
    some body help me . thanks
    You mean *after* running the script, don't you?

    Then I can explain the issue.

    Each script is run into a separate bash session. When you run the script, a new instance of bash is created, and you change the current directory in that new bash instance, but when the script ends, that session is closed, and you return to the parent bash shell, whose working directory hasn't changed, so, indeed, you are still in /root after the script is run.

    What you wan't can be achieved by a bash script, unless you "source" it. When you source a script, its contents is run into the current shell, instead of running into a new instance. So, to achieve the desired effect, you need to do

    Code:
    source my_script.sh
    Or just

    Code:
    . my_script.sh
    The dot is equivalent to the "source" command. You could define an alias to shorten this, however, there's a way that I consider more elegant and is maybe better suited: a function.

    You can put a function like this in your ~/.bashrc and/or ~/.bash_profile files:

    Code:
    function my_func() {
      echo "$PWD"
      cd /mnt/myshell
      echo "$PWD"
    }
    Then you can run it by just using the function in any newly opened shell.

  3. #3
    Just Joined!
    Join Date
    Sep 2008
    Posts
    2
    i92guboj is right
    the problem has resolved
    thank you ~~~

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...