DEV Community

Tony Colston
Tony Colston

Posted on

1 1

bash relative pathing for writing files

Say you have a process that needs to run and writes it logs relative to where it runs.

As a tiny example here is a python program that writes a file using a relative path (the filename is /tmp/cool.py)

outf = open("./dbg.txt","w")
outf.write("hey\n")
outf.close()
Enter fullscreen mode Exit fullscreen mode

If you want to invoke that process from BASH then you have to be careful.

The file dbg.txt will be written relative to your working directory.

So in the example below the dbg.txt file is written in your home directory.

agcc@LAPTOP-BT02BD1T:~$ pwd
/home/agcc
agcc@LAPTOP-BT02BD1T:~$ python /tmp/cool.py
agcc@LAPTOP-BT02BD1T:~$ ls dbg.txt
dbg.txt
Enter fullscreen mode Exit fullscreen mode

That is probably not what you wanted to do. More than likely you needed to change your working directory and then run the python script.

A really great tool to do that is subshell. In BASH that is parens around the commands.

Below I run the set of commands in a subshell. In the new subshell I change to a different directory and execute the python script then verify the file is present. I also printed my working directory.

Finally I executed an ls in my top shell (no longer in a subshell) and there is no file written in that directory.

agcc@LAPTOP-BT02BD1T:~$ (cd /tmp && python cool.py && ls dbg.txt && pwd)
dbg.txt
/tmp
agcc@LAPTOP-BT02BD1T:~$ pwd
/home/agcc
agcc@LAPTOP-BT02BD1T:~$ ls dbg.txt
ls: cannot access 'dbg.txt': No such file or directory
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay