So after an uncomfortable number of hours of trying to do this, this is what I'm trying to do:
Write a bash shell script called direct.sh. This script will take an arbitrary number of command line arguments. Your script should create directories starting with the first argument, then the second directory inside the first one, and then the next one inside the second one, and so on.
For e.g. direct.sh dir1 dir2 dir3
should first create dir1, then create dir1/dir2, then finally create dir1/dir2/dir3
This is what I have done after 20 hours.
#!/bin/bash
for i in $@
do
mkdir -p $1/$i
done
I know its wrong. Please help.
This can be done in a single step, since mkdir -p will create all needed parent directories on the way (that's what the -p option does).
#!/bin/bash
IFS=/
mkdir -p "$*"
Explanation: $* expands to all of the script's arguments, spliced together into a single string, separated by the first character of IFS. That's normally a space character, but here it's set to "/" instead. The double-quotes around it prevent unexpected word-splitting or wildcard expansion.
So, if you run direct.sh dir1 dir2 dir3, it executes mkdir -p "dir1/dir2/dir3", which creates all 3 directory levels (or at least, those that don't already exist).
BTW, in general you should set IFS back to normal after changing it like this. But since there's nothing afterward in the script that might get messed up, and changing it in a script doesn't affect the parent process (the shell you used to run the script), there's no need to set it back in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With