0

I run

#!/bin/bash

id="~/.ssh/foo"

realpath ~/.ssh/foo
realpath "~/.ssh/foo"
realpath $id
realpath "$id"

expecting 4 identical lines of output, with no errors. What I get is

/home/me/.ssh/foo
realpath: '~/.ssh/foo': No such file or directory
realpath: '~/.ssh/foo': No such file or directory
realpath: '~/.ssh/foo': No such file or directory

Why does only the first of these succeed?

I want to do

echo "Enter a path: "
read p
p="$(realpath "$p")"
echo "The real path is $p"

which doesn't work because of this error. What do I need to do?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
spraff
  • 32,570
  • 22
  • 121
  • 229
  • 1
    Change `id="~/.ssh/foo"` to `id=~/".ssh/foo"`. Otherwise the `~` character isn't expanded to your home directory which causes the failure (unless you have directories having literally a `~` character in their name). – pmf Feb 21 '22 at 17:03
  • I need to be able to enter `~/foo` at `read p` – spraff Feb 21 '22 at 17:16
  • 2
    As a quick solution use `realpath "${p/#\~/$HOME}"`. For going more into detail maybe this will help you: [How to manually expand a special variable (ex: ~ tilde) in bash](https://stackoverflow.com/questions/3963716/how-to-manually-expand-a-special-variable-ex-tilde-in-bash) – pmf Feb 21 '22 at 17:24
  • 2
    See [Tilde expansion in environment variable](http://stackoverflow.com/questions/3984074/), [Bash Tilde Expansion](http://stackoverflow.com/questions/4651856/), [Bash problem with with cd using tilde expansion](http://stackoverflow.com/questions/5748216/), [Tilde for home directory doesn't expand within quotes](http://stackoverflow.com/questions/8409024/), and [Tilde expansion in quotes](https://stackoverflow.com/questions/15858766/). – Gordon Davisson Feb 21 '22 at 18:33
  • 1
    Does this answer your question? [How to manually expand a special variable (ex: ~ tilde) in bash](https://stackoverflow.com/questions/3963716/how-to-manually-expand-a-special-variable-ex-tilde-in-bash) – ErikMD Feb 21 '22 at 23:16

0 Answers0