Why does the mkdir command fail with: "No such file or directory"?
#!/bin/bash set -e BIN_DIR="~/bin/" if [ ! -d "$BIN_DIR" ]; then mkdir "$BIN_DIR" fi
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.Sign up to join this community
The error message is produced because the tilde
~ is quoted, as described in Zanna's answer. If you want to use the
~, the relevant part of the script should be:
If for whatever reason you want to quote the string, you can use the environment variable
In my opinion the second approach is better practice.
If a word begins with an unquoted tilde character (`~'), all of the characters preceding the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the value of the shell parameter HOME. If HOME is unset, the home directory of the user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name.
You can remove the quotes, since
~ is the only character in the path
~/bin that will cause the shell to perform an expansion, and we want the expansion in this case. The shell won't perform any further expansions on the result of tilde expansion, at least in Bash 4, which all current or remotely recent releases of Ubuntu have. So even if your home directory contains unusual characters like spaces, it's okay.
Or you can use
$HOME instead of
~, because parameter expansion is not suppressed by double quotes, only by single quotes. The double quotes do ensure that the expanded value is not itself subject to any further expansions, so word splitting or filename expansion will not occur. So
$HOME works even with strangely named home directories, too, so long as you keep the double quotes.