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

前端 未结 15 2171
离开以前
离开以前 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 09:42

    Just to extend birryree's answer for paths with spaces: You cannot use the eval command as is because it seperates evaluation by spaces. One solution is to replace spaces temporarily for the eval command:

    mypath="~/a/b/c/Something With Spaces"
    expandedpath=${mypath// /_spc_}    # replace spaces 
    eval expandedpath=${expandedpath}  # put spaces back
    expandedpath=${expandedpath//_spc_/ }
    echo "$expandedpath"    # prints e.g. /Users/fred/a/b/c/Something With Spaces"
    ls -lt "$expandedpath"  # outputs dir content
    

    This example relies of course on the assumption that mypath never contains the char sequence "_spc_".

提交回复
热议问题