Skip to content

Obtaining the path to a script and/or its containing directory through a symlink #121

@kellytk

Description

@kellytk
#!/usr/bin/env rust-script

// Layout:
// /home/kellytk/symlinkedscript/
// /home/kellytk/symlinkedscript/script/script.rs - this file.
// /home/kellytk/symlinkedscript/symlink/script.rs - symlink (ln -s /home/kellytk/symlinkedscript/script/script.rs /home/kellytk/symlinkedscript/symlink/script.rs)

let path = std::env::var("RUST_SCRIPT_BASE_PATH").expect("fetch failure");

println!(
    "RUST_SCRIPT_BASE_PATH: {:?}",
    path,
);

println!("canonicalized path: {:?}", std::fs::canonicalize(path).expect("canonicalize failure"));

/*
$ pwd
/home/kellytk/symlinkedscript

As expected:
$ ./script/script.rs
RUST_SCRIPT_BASE_PATH: "/home/kellytk/symlinkedscript/./script"
canonicalized path: "/home/kellytk/symlinkedscript/script"

Unexpected:
$ ./symlink/script.rs
RUST_SCRIPT_BASE_PATH: "/home/kellytk/symlinkedscript/./symlink"
canonicalized path: "/home/kellytk/symlinkedscript/symlink"

Expected:
$ ./symlink/script.rs
RUST_SCRIPT_BASE_PATH: "/home/kellytk/symlinkedscript/./script"
canonicalized path: "/home/kellytk/symlinkedscript/script"
*/

How please can the expected result be obtained in both cases?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions