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

前端 未结 15 2317
离开以前
离开以前 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:49

    Expanding (no pun intended) on birryree's and halloleo's answers: The general approach is to use eval, but it comes with some important caveats, namely spaces and output redirection (>) in the variable. The following seems to work for me:

    mypath="$1"
    
    if [ -e "`eval echo ${mypath//>}`" ]; then
        echo "FOUND $mypath"
    else
        echo "$mypath NOT FOUND"
    fi
    

    Try it with each of the following arguments:

    '~'
    '~/existing_file'
    '~/existing file with spaces'
    '~/nonexistant_file'
    '~/nonexistant file with spaces'
    '~/string containing > redirection'
    '~/string containing > redirection > again and >> again'
    

    Explanation

    • The ${mypath//>} strips out > characters which could clobber a file during the eval.
    • The eval echo ... is what does the actual tilde expansion
    • The double-quotes around the -e argument are for support of filenames with spaces.

    Perhaps there's a more elegant solution, but this is what I was able to come up with.

提交回复
热议问题