Reputation: 13
so I am trying to make a bash script loop that takes a users file name they want and the number of files they want and creates empty files. I made the script but I keep getting the error "./dog.sh: line 6: 0]: No such file or directory". I'm new to bash script and don't know what I'm doing wrong. Any help would be awesome thanks!
#!/bin/bash
echo "what file name do you want?"; read filename
echo "how many files do you want"; read filenumber
x=$filenumber
if [$x < 0]
then
touch $fiename$filenumber
x=$((x--))
fi
Upvotes: 1
Views: 149
Reputation: 113834
for x in $(seq "$filenumber"); do touch "$filename$x"; done
seq $filenumber
produces a list of numbers from 1 to $filenumber
. The for
loop assigns x
to each of these numbers in turn. The touch
command is run for each value of x
.
In bash
, if we can type the correct file number into the command line, the same thing can be accomplished without a for
loop:
$ touch myfile{1..7}
$ ls
myfile1 myfile2 myfile3 myfile4 myfile5 myfile6 myfile7
{1..7}
is called "brace expansion". Bash will expand the expression myfile{1..7}
to the list of seven files that we want.
Brace expansion does have a limitation. It does not support shell variables. So, touch myfile{1..$filenumber}
would not work. We have to enter the correct number in the braces directly.
Upvotes: 1
Reputation: 818
#!/bin/bash
echo "what file name do you want?"; read filename
echo "how many files do you want"; read filenumber
x=$filenumber
while [ $x -gt 0 ]; do
touch $filename$x
x=$(( $x - 1))
done
Upvotes: 0
Reputation: 5070
Maybe it's a typo: $fiename instead of $filename
also, you might want some kind of loop like so:
x=1
while [ $x -le $filenumber ]; do
touch $filename$x
let x=x+1
done
Upvotes: 0