Reputation: 93
I'm new in bash scripting. I have two questions:
Is it possible to save a script output to a text file with a unique file name every time i run the script?
Can I put all of these (the command that will generate the output of the script, the looping of file name and the command saving the iterating file name to a text file) in one script?
Upvotes: 1
Views: 3058
Reputation: 34698
1. Is it possible to save a script output to a text file with a unique file name every time i run the script?
Yes.
2. Can I put all of these (the command that will generate the output of the script, the looping of file name and the command saving the iterating file name to a text file) in one script?
Yes.
This script for example does that:
#!/bin/sh
COUNTER=1
while true; do
FILENAME="filename($COUNTER)"
if [ -e $FILENAME ]; then
COUNTER=$(($COUNTER+1))
else
break
fi
done
your_command > $FILENAME
Upvotes: 2
Reputation: 6275
(1) Absolutely! You just need a way to generate a unique filename. There are several ways to do this...
# way 1 - use the bash variable $RANDOM
$ export MYFILE=outputfile_$RANDOM
# way 2 - use date (unique to every second)
$ export MYFILE=outputfile_`date +%Y%m%d%H%M%S`
# way 3 - use mktemp
$ export MYFILE=`mktemp outputfile_XXXXXXXX`
$ ./myscript > $MYFILE
(2) Sure!
Starting your script with this line - I'll pretend this file is called commands.sh
#!/bin/bash
Then set the execute permission for the file
$ chmod 750 commands.sh
# you can now run this file using...
$ ./commands.sh
(3) Want incrementing numbers on temporary files? (Be careful about the smooth parens, then need to be escaped properly using the backslash "\")
$ export I=1
$ while [ -f filename\($I\) ]; do export $I=`expr $I + 1`; done
$ ./myscript.sh > filename\($I\)
Upvotes: 2