8

Now, this is a strange problem, I have this kind of script:

CWD="$(cd -P -- "$(dirname -- "$0")" && pwd -P)"
RESOURCES_PATH="${CWD}/resources"

PROJECT_NAME="something"

DRUSH_ALIASES_EXAMPLE_PATH="${RESOURCES_PATH}/example.aliases.drushrc.php"
DRUSH_ALIASES_PATH="~/.drush/${PROJECT_NAME}.aliases.drushrc.php"

cp ${DRUSH_ALIASES_EXAMPLE_PATH} ${DRUSH_ALIASES_PATH}
echo "cp ${DRUSH_ALIASES_EXAMPLE_PATH} ${DRUSH_ALIASES_PATH}"

When I'm trying to run that kind of script, I'm getting error: "cp: Cannot create regular file "~/.drush/something.aliases.drushrc.php". There is no such file or directory"

But the funny thing is, that if I will copy the output of "echo" and paste in directly into terminal, the command will work just fine. I'm confused, any ideas what can be wrong with above script?

3 Answers 3

13

Try using $HOME/.drush... instead of ~/.drush.... the "~" does not seem to be expanded to your home directory.

2
  • 6
    Yep, because ~ is not expanded when quoted. Of course, the arguments to cp really ought to be quoted as well, to avoid surprises.
    – derobert
    Dec 2, 2013 at 13:19
  • 1
    ~/"quoted name" will work, as well. Dec 2, 2013 at 14:49
2

The tilde ~ character to mean the home directory only works at the beginning of a word, at the beginning of a value being assigned, or (for the purposes of PATH assignments) after a colon in a value being assigned. It must not be quoted.

Since ~ is expanded by the shell, the fact that you see it reported by cp means that you have a shell expansion problem.

Here the tilde is within double quotes, so it isn't expanded. Use either of these:

DRUSH_ALIASES_PATH=~/".drush/${PROJECT_NAME}.aliases.drushrc.php"
DRUSH_ALIASES_PATH="$HOME/.drush/${PROJECT_NAME}.aliases.drushrc.php"
0

Using bash you can also use internal string subsitution via parameter expansion to replace the tilde character ~ with the value of $HOME.

Not very elegant, but could be useful if you are uncertain about a possible ~ character in a file path string passed on to you (not the case here).

unset HOME
HOME="$(eval 'echo ~')"

- cp ${DRUSH_ALIASES_EXAMPLE_PATH} ${DRUSH_ALIASES_PATH}
+ cp "${DRUSH_ALIASES_EXAMPLE_PATH/#\~/${HOME}}" "${DRUSH_ALIASES_PATH/#\~/${HOME}}"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .