0

Consider this tiny script:

# script.sh
echo $@

If I call it like this ./script.sh ~/docs, I get /home/me/docs as output. However, I need it to echo ~/docs. How can I achieve that?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
coderodde
  • 1,269
  • 4
  • 17
  • 34
  • `echo ${1/$HOME/\~}` Using the parameter-expansion with text replacement to replace the directories `/home/youruser` from the first program argument with `~`. You can use the `$HOME` variable that contains `/home/youruser` in the expansion to make it generally apply to any user. You must escape the `~` with `\~` to prevent further tilde expansion by the shell. – David C. Rankin Feb 21 '22 at 07:19
  • 3
    The tilde-expansion does not happen in your script, but on the calling side. There is no way to find out how exactly the caller typed the command line invoking your program; you see only what the shell passes to you. – user1934428 Feb 21 '22 at 11:31

1 Answers1

4

It's not under the script's control. It's up to the user. They must quote the tilde to prevent it from being expanded. Options include:

./script.sh \~/docs
./script.sh '~/docs'
./script.sh "~"/docs
John Kugelman
  • 349,597
  • 67
  • 533
  • 578