sgmoore
sgmoore

Reputation: 16067

Change Directory and exit program in that directory in Linux

I have a simple program that I run from a terminal which changes the working directory (via setCurrentDir) and performs some other work which creates some new files in that folder. When the program has completed, I would like the terminal prompt to remain in that folder rather than return to the original directory.

As far as I know, this is a linux issue, rather than a Nim issue, but I am wondering if there is any workaround in Nim.

Upvotes: 1

Views: 241

Answers (1)

shirleyquirk
shirleyquirk

Reputation: 1598

This should not be possible, and indeed isn't, without hacking the parent process using gdb in accordance with How do I set the working directory of the parent process?

Indeed, Do Not Do This.

import std/[os,osproc,strformat]

proc getppid():int32{.importc,header:"unistd.h".}

let f = open("/tmp/gdb_cmds",fmWrite)
f.write(&"""p (int) chdir ("{commandLineParams()[0]}")
detach
quit
""")
f.close()

discard execCmd(&"sudo gdb -p {getppid()} -batch -x /tmp/gdb_cmds;rm /tmp/gdb_cmds")

usage:

/tmp$ nim c cd.nim
/tmp$ mkdir child
/tmp$ touch you_are_in_parent_dir
/tmp$ touch child/you_are_in_child_dir
/tmp$ ls
you_are_in_parent_dir
cd.nim
cd
child
/tmp$ ./cd child
/tmp$ ls #<---notice pwd is cached
you_are_in_child_dir
/tmp$

Upvotes: 1

Related Questions