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 :

./script.sh 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.


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”.

  • You right ! If I use directly /share/homes/$user_variable instead of ~$user_variable it works. Thank you. – jbltx Jan 20 '15 at 23:48

The ordering of expansions here does not stop you from using the variable according to your original intention. Usually eval can help when it comes to dynamic commands.

eval "echo \"export USER_VAR=$user_variable\" > ~$user_variable/.filename"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.