1

I'm new in bash scripting. I have two questions:

  1. Is it possible to save a script output to a text file with a unique file name every time i run the script?

  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?

Andy Jones
  • 6,205
  • 4
  • 31
  • 47

2 Answers2

2

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
Robert Siemer
  • 32,405
  • 11
  • 84
  • 94
2

(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\)
Andy Jones
  • 6,205
  • 4
  • 31
  • 47
  • Thank you, sir! I tried the mktemp and it worked. If I want to use the mktemp and want the filename to have something like (1),(2),(3), what should I do? I want my files to be named like this: filename(1), filename(2). – endlesslearning Jan 08 '14 at 02:50
  • It works but I think I'll have to go with the other answer. I wish I could upvote you or something but I dont have that privilege yet :( Thank you and I really appreciate it. – endlesslearning Jan 08 '14 at 03:17
  • @endlesslearning merry christmas, you can upvote now :) (anonymous vote elf) – Andy Jones Jan 08 '14 at 03:19