0

I am attempting to write a 1 line while loop that creates a string of file names like list="temp0.txt temp1.txt temp2.txt ... " etc.. I want it to be a random number of files between 0 and 50, and this is what I have thus far.

argumentCount=$RANDOM
let "argumentCount %= 50"
i=0
list=""
while [ $i -lt $argumentCount ]; do; touch temp[$i].txt; $list="$list temp[$i].txt; ((i=i+1)); done
countLines $list > output.txt

I am trying to declare a random number between 0 and 50, and then using a while loop I want to create the same number of files as this random number. I want to then create a string that has all of the file names listed one after the other. This string will then be passed to countLines, which is a program that accepts any number of filenames as parameters.

I have this set of commands stored in a different file, and I am using eval on each line in this file, but it is giving me a syntax error. Is there something I can do to make it work? Thanks

6
  • printf -v varname "temp%03d.txt" $(($RANDOM % 50)) Then $varname will contain temp000.txt - temp049.txt randomly. (you can control the number of leading '0's with the printf format specifier. (add $(($RANDOM % 50 + 1)) for 001 - 050 numbering). Commented Feb 5, 2017 at 4:29
  • I am looking to make multiple files, but a random number of files. Commented Feb 5, 2017 at 4:34
  • @SeanMorgan: Can you provide a minimal verifiable input and expected output. Your current code/requirement is not clear. State exactly your input and output required Commented Feb 5, 2017 at 4:36
  • You need some exit condition for your loop. You just can't continue to randomly create files forever. You can use a counter (e.g. declare -i n=0) and in your file-create loop to ((n++)) and test "$n" -gt '40' && break if you like. (or whatever number you like). You also need to check for an existing file of the same name/number (e.g. test -f "$varname" && continue to generate a non-conflicting filename) Commented Feb 5, 2017 at 4:37
  • In your existing while loop line, try dropping the ';' after do and '$' in '$list=' Commented Feb 5, 2017 at 4:41

1 Answer 1

1

This will print a line with file names:

eval echo temp{1..$((RANDOM%50))}.txt

And this will touch the list of files:

eval touch temp{1..$((RANDOM%50))}.txt

And this script will do all the things yours do:

#!/bin/bash

list=$( eval echo '"temp["{1..'$((RANDOM%50))'}"].txt"' )

touch $list

countLines "$list" > output.txt
Sign up to request clarification or add additional context in comments.

Comments

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.