LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   when to quote or not to quote variable names - mktemp problem (http://www.linuxquestions.org/questions/linux-newbie-8/when-to-quote-or-not-to-quote-variable-names-mktemp-problem-706292/)

glinux 02-20-2009 03:50 PM

when to quote or not to quote variable names - mktemp problem
 
Hi,

double quotes in a variable name causes problems for mktemp when run from a shell script; in particular:

# following fails: quotes in $parent
parent="~/tmp"
mktemp -d -p $parent prefix.XXXX

# following fails, even though $grandparent that is assigned to $parent,
# is not explicitly quoted
grandparent="~/tmp"
parent=$grandparent
mktemp -d -p $parent prefix.XXXX

# removing quotes fixes problem,
grandparent=~/tmp
parent=$grandparent
mktemp -d -p $parent prefix.XXXX

but the solution negates the reason for quoting variables - a standard convention when scripting.

could someone explain why the quoted values for the variables causes mktemp to fail? and is this specific to mktemp? i haven't tried this for single quotes.

glinux

colucix 02-20-2009 04:02 PM

The problem here is the order of the shell expansion. The variable expansion is done after tilde expansion, so that when the $parent is expanded to its value, the tilde remains literal. You can use the eval command to perform a further expansion. Removing the double quotes let the shell to expand the value of $parent immediately during the assignment.

glinux 02-20-2009 04:20 PM

thanks for explanation

so there's two expansions that should happen for the variable to resolve to it's expected value: there's the variable expansion or substitution which results in a literal tilde and secondly, a tilde expansion, which is inhibited by the double quotes.

glinux

colucix 02-20-2009 04:37 PM

Correct. The quoting prevents reinterpretation of all special characters within the quoted string, except $, ` (backquote), and \ (escape) (cited from the Advanced Bash Scripting Guide). So the ~ in ~/tmp is not expanded and when passed to the mktemp command the variable substitution is performed with no possibility for the tilde expansion (due to the order of the expansion as explained above).

Of course, this behaviour is common to all the commands (not specific to mktemp). For example, consider the following:
Code:

$ pwd
/home/colucix/test
$ my_dir="~"
$ cd $my_dir
bash: cd: ~: No such file or directory
$ pwd
/home/colucix/test
$ my_dir=~
$ cd $my_dir
$ pwd
/home/colucix



All times are GMT -5. The time now is 11:15 AM.