1

I want to create a directory given in a variable value. First let's ensure the directory can be created via the simplest command:

$ mkdir ~/opt
[ec2-user@ip-172-31-15-193 ~]$ ls ~/opt
[ec2-user@ip-172-31-15-193 ~]$ ls -l ~/opt
total 0

What is the syntax for using a variable in place of the hard-coded path? Here is what has been tried:

$ BDIR="~/opt"
$ mkdir $BDIR
mkdir: cannot create directory ‘~/opt’: No such file or directory

Also:

$ mkdir "$BDIR"
mkdir: cannot create directory ‘~/opt’: No such file or directory

1 Answer 1

5

Normally what you're doing would work. It's the "~" character that's tricking you here.

You cannot use "~" outside a bash prompt because it's a shell expansion.

You need to explicitly use the $HOME variable:

BDIR="$HOME/opt"

Or you can omit the quote signs, this way the BDIR assignment will be to the expanded path and it will work:

BDIR=~/opt

(if needed, you can escape spaces with slashes - BDIR=~/path\ with\ spaces ).

Or, as @Attie suggested, keep the tilde outside the quotes:

BDIR=~"/opt"
5
  • Thx - will award in a few.. Apr 6, 2019 at 22:57
  • 2
    ~"/opt" would also work... useful if spaces are an issue
    – Attie
    Apr 6, 2019 at 23:11
  • It's worth noting that no such file or directory refers to the directory literally named ~ in the OP's current working directory. If it existed, the troublesome command would create opt directory there. Apr 7, 2019 at 2:44
  • 3
    @Attie For reasons I'm not clear on, the / sometimes also needs to be unquoted. That is, ~"/opt" might work, but ~/"opt" will work. Apr 7, 2019 at 5:57
  • Interesting, thanks @GordonDavisson ... I've not noticed that as an issue before, but I'll bear it in mind.
    – Attie
    Apr 7, 2019 at 10:34

You must log in to answer this question.

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