Linux – Echo in file returns No such file or directory

bashcommand lineecholinux

I'm wondering why my simple script doesn't work:

#!/usr/bin/env bash
echo "export USER_VAR=$user_variable" > ~$user_variable/.filename

When I launch the script I have this error :

./ admin: line 3: ~admin/.filename: No such file or directory 

Of course, the directory for ~admin exists:

~ # cd ~admin
/share/homes/admin #

And if I test this kind of command directly in command-line, it works:

# echo "test" > ~admin/.filetest

So why my echo command doesn't work in script file ?

Thank you.

Best Answer

From bash(1):

The order of expansions is: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and pathname expansion.

I.e., it does tilde expansion before variable expansion, so it doesn’t replace $user_variable with $1 (which, I assume, is “admin”) until after it has tried and failed to process the ~ – because it is looking for a user named “$user_variable” rather than a user named “admin”.

Related Question