I am writing the following shell script for generating multiple directories by providing arguments.
This is my shell script "createDirectories1.sh"
#!/bin/bash
echo "$1"
echo "$2"
echo "$3"
mkdir $1{$2..$3}
#command mkdir $1{$2..$3}
And I am running the above script using following command
bash createDirectories1.sh week 1 5
And my expected output is
Expected output
This is how my terminal looks when giving commands to execute the script
I am not sure when I am running this command mkdir week{1..5} it works fine but when i run the same using shell script its not working
please help and let me know what modification is needed in my shell script ??
5
Answers
You must use
eval
command. The eval command first evaluates the argument and then runs the command stored in the argument.bash ranges work with literals, not variables, so you need some way to
eval
{$2..$3}
; the problem witheval
ing a string is that you have to ensure that it won’t bite you:this is what you need.
Let you know this answer :
https://askubuntu.com/questions/731721/is-there-a-way-to-create-multiple-directories-at-once-with-mkdir
Use for loop:
First, I think your premise is flawed.
Why? You could make a loop with on one line if that were somehow important, but it really shouldn’t be. If it’s an assignment, be aware that your instructor is probably expecting an
eval
and (if they are any good) planning to screw you with it.But there are still ways, if you allow for the fact that there’s always a loop under the hood somewhere. For example –
That’s "one line", though it could just as well be written as
You could make it
It’s still executing a subshell, but it’s "one line", and
xargs
&seq
aren’t exactly loops. This also doesn’t useeval
, so it’s a lot safer.Now the whole script is
And if I run it as
./tst 1 ";echo rm -fr ~;" 3
then it successfully fails without executing any malicious code.
but with valid args it’s good.