Reputation: 1265
I'm looking for a Bash equivalent of Python's os.path.join. I'm trying to prompt the user for a directory path, which then will be used (with the help of path join equivalent) to do other stuff.
Upvotes: 1
Views: 2633
Reputation: 77
You might be looking for the readlink
command. You can use readlink -m "some/path"
to convert a path to the canonical path format. It's not quite path.join but it does provide similar functionality.
Edit: As someone pointed out to me readlink
is actually more like os.path.realpath
. It is also a GNU extension and not available on all *nix systems. I will leave my answer here in case it still helps in some way.
Upvotes: 1
Reputation: 365835
It's perfectly safe to use, e.g., "${dirpath}/${filename}"
in a bash
script.
bash
only understands POSIX-style pathnames. Even if you build a MinGW/native bash
on Windows. That means /
is always the path separator. And it means that it never hurts to put two slashes in a row, so even if $dirpath
happens to end in '/', everything is fine.
So, for example:
$ cat join.sh
#!/bin/bash
echo -n 'Path: '
read dirpath
echo -n 'Filename: '
read filename
ls -l "${dirpath}/${filename}"
$ ./join.sh
Path: /etc/
Filename: hosts
-rw-r--r-- 1 root wheel 236 Sep 15 2014 /etc/hosts
In Python, it's not safe to just use /
this way. Python handles native-format pathnames on POSIX and POSIX-like systems, but also handles native-format pathnames on Windows.*, in which the path separator is \
, two backslashes have a special meaning in certain places, you have drive letters to worry about, etc. So, you have to use os.path.join
to be portable.
* It also has code for classic Mac (which uses colons), VMS (which uses a mix of different things that you don't want to know about), etc., if you're using an old enough Python.
Upvotes: 2