How to manually expand a special variable (ex: ~ tilde) in bash

前端 未结 15 2421
离开以前
离开以前 2020-11-22 09:34

I have a variable in my bash script whose value is something like this:

~/a/b/c

Note that it is unexpanded tilde. When I do ls -lt on this

15条回答
  •  再見小時候
    2020-11-22 10:00

    I have done this with variable parameter substitution after reading in the path using read -e (among others). So the user can tab-complete the path, and if the user enters a ~ path it gets sorted.

    read -rep "Enter a path:  " -i "${testpath}" testpath 
    testpath="${testpath/#~/${HOME}}" 
    ls -al "${testpath}" 
    

    The added benefit is that if there is no tilde nothing happens to the variable, and if there is a tilde but not in the first position it is also ignored.

    (I include the -i for read since I use this in a loop so the user can fix the path if there is a problem.)

提交回复
热议问题