shellmkdirmkdirs

Assign output of mkdir command to variable


I am trying to assign the output of mkdir command to a variable. So I can use the directory further.

-bash-4.1$ pwd
/user/ravi/myscripts/tmpdata
-bash-4.1$ OUTPUT=$(mkdir tmpbkp.`date +%F`)
-bash-4.1$ ls | grep tmp
tmpbkp.2017-04-06
-bash-4.1$ echo "$OUTPUT"

But the directory name is not assigning to the variable. Could you please correct me where I am wrong.


Solution

  • When you run the mkdir command by itself, look how much output it produces:

    $ mkdir foo
    $
    

    None!

    When you use a command substitution to generate the argument to mkdir, look how much extra output you get:

    $ mkdir tmpbkp.`date +%F`
    $
    

    None!

    When you put it inside $() it still produces no output.

    There is a -v option for mkdir (in the GNU version at least) which produces some output, but it's probably not what you want.

    You want the name of the directory in a variable? Put it in a variable first, then call mkdir.

    $ thedir=tmpbkp.`date +%F`
    $ mkdir $thedir
    $ echo $thedir
    tmpbkp.2017-04-06
    $