0

The string variable here is the pathname to some file. Should be a simple solution, possibly useful to others.

This problem came up while I was writing a simple bash function in my .bashrc; see this thread.

Luke Davis
  • 2,548
  • 2
  • 21
  • 43
  • 1
    If you really want `~` -> `$HOME`, as opposed to the other direction, there's a **long** and comprehensive answer elsewhere on the site, but I doubt it's helpful to you. Which is to say, you should really specify only the direction you actually need. – Charles Duffy Jul 26 '17 at 05:09
  • see https://stackoverflow.com/questions/3963716/how-to-manually-expand-a-special-variable-ex-tilde-in-bash (re: question with said comprehensive answers which are almost certainly useless to you). – Charles Duffy Jul 26 '17 at 05:10
  • I wanted the other direction, but I just tried out [this answer](https://stackoverflow.com/a/27485157/4970632) by swapping the `$HOME` and `~` in his parameter expansion method... and it worked just fine. Thanks for the tip. – Luke Davis Jul 26 '17 at 05:16

1 Answers1

1

~ -> $HOME

This is duplicative of How to manually expand a special variable (ex: ~ tilde) in bash


$HOME -> ~

This is one of those places where you're better off fixing your users than adding workarounds (which are likely to have surprising effects) to your code. That said...

copy() {
  local src=$1 dest=$2
  [[ $dest = $HOME/* ]] && dest="~/${dest#"$HOME/"}"
  scp "$src" "$dest"
}
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441