0

I want to write a bash script that will get a command line argument and create nested directories under the user home directory. E.g a/b/c

mkdir -p $1/$2/$3

But I want create not just three levels of directories, I want get command line argument 3 or 5 and create necessary quantity of nested directories

4
#!/bin/sh

(
    IFS=/
    mkdir -p "$*"
)

The expansion of "$*" will be a single quoted string consisting of all arguments to the script concatenated together with the first character of $IFS as a delimiter. This is why we also set $IFS to /.

I'm running that in a subshell to avoid setting IFS for the rest of the script (it changes the behavior of certain things, like how read works). If there's nothing else in the script, you can leave ( and ) out.

Testing:

$ tree
.
`-- script.sh

0 directory, 1 file
$ ./script.sh 1 2 3 4 {a..k}
$ tree
.
|-- 1
|   `-- 2
|       `-- 3
|           `-- 4
|               `-- a
|                   `-- b
|                       `-- c
|                           `-- d
|                               `-- e
|                                   `-- f
|                                       `-- g
|                                           `-- h
|                                               `-- i
|                                                   `-- j
|                                                       `-- k
`-- script.sh

15 directories, 1 file
0

You can set the inter field separator $IFS to /, then "$*" will expand to a/b/c/...:

IFS=/
mkdir -p "$*"
1

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.