View previous topic :: View next topic |
Author |
Message |
guyuming Apprentice
Joined: 19 Nov 2020 Posts: 252
|
Posted: Fri Jan 10, 2025 7:40 am Post subject: how to read in user input ~/Downloads and resolve the ~? |
|
|
I need to read user input file path such as ~/Download with readline history, and resolve it with realpath.
however, the file_path variable value seems to have single quotation mark around it, so realpath says file not found in Chinese.
but if i echo $file_path, no single quotation mark shown.
How can I resolve user input from ~/Downloads into /home/guyuming/Downloads then?
Code: | guyuming@localhost ~ $ read -e -r file_path
~/Downloads
guyuming@localhost ~ $ realpath $file_path
realpath: '~/Downloads': 没有那个文件或目录
guyuming@localhost ~ $ echo $file_path
~/Downloads
guyuming@localhost ~ $ realpath '~/Downloads'
realpath: '~/Downloads': 没有那个文件或目录
guyuming@localhost ~ $ realpath ~/Downloads
/home/guyuming/Downloads
guyuming@localhost ~ $ |
|
|
Back to top |
|
|
grknight Retired Dev
Joined: 20 Feb 2015 Posts: 1977
|
Posted: Fri Jan 10, 2025 2:03 pm Post subject: |
|
|
The reason why the last manual attempt works is because the shell expands the ~ before realpath sees it. The variable never is single quoted.
A way around this is to expand any leading ~ to $HOME after the read: Code: | file_path="${file_path/#~/${HOME}}" |
This may not work in all shells, but it definitely works in bash. |
|
Back to top |
|
|
guyuming Apprentice
Joined: 19 Nov 2020 Posts: 252
|
Posted: Fri Jan 10, 2025 2:21 pm Post subject: |
|
|
grknight wrote: | The reason why the last manual attempt works is because the shell expands the ~ before realpath sees it. The variable never is single quoted.
A way around this is to expand any leading ~ to $HOME after the read: Code: | file_path="${file_path/#~/${HOME}}" |
This may not work in all shells, but it definitely works in bash. |
Thank you very much! I had scratched my head on this for one day. |
|
Back to top |
|
|
|