1

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
2
  • 1
    Consider running your script through shellcheck first to clear up the basic issues, then ask about the remainder. Commented Nov 4, 2014 at 23:03
  • x=$((x--)) is really funny ;). Commented Nov 4, 2014 at 23:06

3 Answers 3

1
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.

Alternative

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

That fixed my problem of running it but all I get is just one file with the number. ex. dog and 7 = dog7. I need it to make dog1, dog2, dog3,... dog7.
Thanks! I see where my problem is now. Thanks for all the help.
0
#!/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

1 Comment

trying to keep this as true to your example as possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.