help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] No tilde expansion in [[..]] when reading input with rea


From: Suvayu Ali
Subject: Re: [Help-bash] No tilde expansion in [[..]] when reading input with read
Date: Mon, 25 Feb 2013 14:32:44 +0100
User-agent: Mutt/1.5.21 (2012-12-30)

Hello Chris,

On Mon, Feb 25, 2013 at 09:08:12AM +0800, Chris Down wrote:
> Here it is with the dependency on `awk' removed (no external dependencies):
> 
>     tildeExpand() {
>         local path=$1
> 
>         if [[ $path =~ ^~$ || $path =~ ^~/ ]]; then
>             path=${path/\~/$HOME}
>         elif [[ $path =~ ^~([[:alnum:]]+) ]]; then
>             user=${BASH_REMATCH[1]}
>             while IFS=: read -r pUser _ _ _ _ pHome _; do
>                 if [[ $user == $pUser ]]; then
>                     userHome=$pHome
>                     break
>                 fi
>             done < /etc/passwd
>             if [[ $userHome ]]; then
>                 path=${path/\~$user/$userHome}
>             fi
>         fi
> 
>         printf '%s\n' "$path"
>     }

Both variations work very well.  Thanks a lot.  :)

Now to my question, I understand what you mentioned earlier about the
tilde being literal when read via read.  What I do not understand is why
it is not expanded when inside [[...]], since the docs say the
following:

`[[...]]'
          [[ EXPRESSION ]]

     Return a status of 0 or 1 depending on the evaluation of the
     conditional expression EXPRESSION.  Expressions are composed of
     the primaries described below in *note Bash Conditional
     Expressions::.  Word splitting and filename expansion are not
     performed on the words between the `[[' and `]]'; tilde expansion,
     parameter and variable expansion, arithmetic expansion, command
     substitution, process substitution, and quote removal are
     performed.  Conditional operators such as `-f' must be unquoted to
     be recognized as primaries.

Okay while writing the email I did a quick test:

  $ [[ -d ~/ ]] && echo exists || echo not there
  exists
  $ tmp='~/'
  $ [[ -d $tmp ]] && echo exists || echo not there
  not there

So I guess this means the variable is being expanded but then the tilde
in the expanded string is not further expanded (it is literal).  I guess
that is reasonable behaviour.  Is there anyway to handle situations like
these?  It is probably common enough so there must be solutions out
there which doesn't involve case-specific parsing of the expanded
string.

Any thoughts?

-- 
Suvayu

Open source is the future. It sets us free.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]