I do not know how to write that part of bash script which enables me to write to the file which is created in the middle of the script (because it depends on user input) but I want to write output from the beginning.


 read -p "Enter your city: " city
 touch ${city}

Script does not know what user put in city so if I am correct I am not able to logging from <start_of_logging> part or is there any workaround? I mean I want to log everything from the beginning and write it out to the file which is called like a city provided by an user.

  • Did you try some searching? What about this?: stackoverflow.com/a/3215760/6607497
    – U. Windl
    Jan 28 at 20:22
  • Two ways: (1) Start logging to a file as /tmp/myIniqName, and mv this file as soon as you find what the final name should be. (2) Send your log lines to an array until you find the final name, then write out the array to the file, and send subsequent logs to the real file. Jan 28 at 22:37
  • Yes, it works with mv approach. Thanks @Paul_Pedant.
    – sqr
    Jan 29 at 15:28
  • @U.Windl I think the OP wants to log to e.g. ./Memphis.log, including any logging done before the user enters his city. Jan 29 at 16:28
  • 1
    @Paul_Pedant Today I'd strongly advise to use mktemp to create the log file (instead of using some fixed initial name), unless the computer is strictly single-user.
    – U. Windl
    Jan 30 at 7:23

1 Answer 1


So to summarize the comments, the code could be something like this:

### start logging using temporary logfile
logfile="$(mktemp)" # possibly add options to mktemp, like "-p dir" as needed

# add a message to logfile
    echo "$@" >> "$logfile"
### code
 read -p "Enter your city: " city
 touch ${city}
### update logfile
log "renaming temporary logfile $logfile to $newlogfile"
mv "$logfile" "$newlogfile" && logfile="$newlogfile"
log "now logging to $logfile"

When running the script with input "testtown", I got:

Enter your city: testtown
me@pc:~> cat something_with_testtown.log
renaming temporary logfile /tmp/tmp.alKCBTV7ti to something_with_testtown.log
now logging to something_with_testtown.log

Important note

Hopefully nobody enters :; rm -rf / (or similar) as city...

  • Double-quote your variables when you use them and you can guarantee the rm concern won't be a worry. You might want to sanitise city though to ensure it doesn't contain / Jan 30 at 11:45
  • My "Important note" was aimed towards the OP, as the question was the logfile should be "$city" (as I understand it). Of course the logfile (as I suggested) could be derived from the city name (with some sanitizing applied).
    – U. Windl
    Feb 1 at 6:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .