How can I convert a file path to an URI in the command-line?


/home/MHC/directory with spaces and ümläuts



5 Answers 5


One way to do this is using urlencode (install it on Ubuntu via sudo apt-get install gridsite-clients).

urlencode -m "$filepath"

will convert the path to an URI. The "file://" part of the URI will be left out, but you can easily add that via a bash one-liner:

uri=$(urlencode -m "$1"); echo "file://$uri"

or directly

echo "file://$(urlencode -m "$1")"


echo -n file://; urlencode -m "$1"

Many thanks to Michael Kjörling for the references!

  • Don't forget the quotes! You probably want encodeduri=$(urlencode -m "$uri") with $uri in double quotes! Dec 26, 2012 at 21:49
  • @gniourf_gniourf Thank you, modified the code accordingly. Dec 26, 2012 at 21:55
  • Fails for me, transforms "é" to "%FF%FF" (on Debian Buster) Sep 7, 2020 at 19:44
  • Also didn't work for me, I got a bunch of %FF for cyrillic symbols. Oct 24, 2020 at 8:13

On CentOS, no extra dependencies needed:

$ python -c "import urllib;print urllib.quote(raw_input())" <<< "$my_url"
  • 1
    With pathlib module it could be done via python -c 'import sys,pathlib; print(pathlib.Path(sys.argv[1]).resolve().as_uri())' "$my_url"
    – umi
    Jun 19, 2019 at 18:53
  • 1
    pathlib is only available in Python 3, which is not installed by default on CentOS.
    – Rockallite
    Jun 20, 2019 at 2:06
  • raw_input() was renamed to input() in Python3
    – Mendhak
    Nov 14, 2021 at 8:43

You can also use the Perl module URI::file directly from the command line:

$ path="/home/MHC/directory with spaces and ümläuts"
$ echo $path | perl -MURI::file -e 'print URI::file->new(<STDIN>)."\n"'
  • 1
    Can be shortened to echo $path | perl -MURI::file -E 'say URI::file->new(<>)' with Perl 5.10 (from year 2007) or newer Apr 2, 2019 at 22:24

Rockallite gave a good answer, but I didn't want to type that every time.

I made a reusable bash function to do this called "file2url". To see where to save bash functions, take a look at this thread on SO.

file2url () {
    python -c "import sys, pathlib; print(pathlib.Path(input()).resolve().as_uri())" <<< $1

This assumes that you have a python3 installed with the name "python".

  • sys doesn't seem to be used
    – Kiruahxh
    Jun 20, 2023 at 14:01

You can pass path as argument to the following script:

#!/usr/bin/env gjs

const { Gio } = imports.gi;

let path = Gio.File.new_for_path(ARGV[0]);
let uri = path.get_uri();

To convert from uri to path use the following script:

#!/usr/bin/env gjs

const { Gio } = imports.gi;

let uri = Gio.File.new_for_uri(ARGV[0]);
let path = uri.get_path();

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .