Search code examples
linuxbashwhiptail

Bash whiptail dies when changing directory


I'm trying to change to a directory and run additional commands within my whiptail dialog screen, but after cloning my git repository it seems that my script is now dying when trying to change to the directory:

STATUS=0
touch log.txt
while [ $STATUS -lt "100" ]; do
  echo "cloning Repo" >> log.txt
  git clone [email protected]:abc/repo.git /repo >> log.txt 2>&1
  echo "changing directory" >> log.txt
  cd /repo >> log.txt 2>&1
  echo `pwd`
  echo "installing bundler" >> log.txt
  gem install bundler --no-ri --no-rdoc >> log.txt 2>&1
  (( STATUS += 99 ))
  echo $STATUS
done | whiptail --gauge "Setting Up Neo (THIS WILL TAKE SOME TIME)..." 40 78 0
;;

Logging commands with set -x, this looks like:

:66+STATUS=0
:67+touch log.txt
:149+whiptail --gauge 'Setting Up (THIS WILL TAKE SOME TIME)...' 40 78 0
:68+'[' 0 -lt 100 ']'
:71+echo 'apt-get update'
:73+((  STATUS += 15  ))
:74+echo 15
:77+echo 'apt-get upgrade'
:79+((  STATUS += 15  ))
:80+echo 30
:83+echo 'apt-get -y git-all'
:85+((  STATUS += 15  ))
:86+echo 45
:111+((  STATUS += 30  ))
:112+echo 75
:115+rm -rf /repo
:116+echo 'cloning Repo'
:117+git clone [email protected]:abcd/repo.git /repo
:118+echo 'changing directory'
:119+cd /repo
::120+pwd
:120+echo /repo
:121+echo 'installing bundler'
:122+gem install bundler --no-ri --no-rdoc
:148+echo 100
:68+'[' 100 -lt 100 ']'
:5+true
::11+whiptail --title 'Configuration Menu' --menu 'Choose an option' 40 78 30 1 'Show current configuration.' 2 'Setup Wizard.' 0 Exit

The output of log.txt stops at changing directory and my whiptail menu goes back to the main page (as if the setup is done, but it's not since I should also see the pwd and installing bundler in the log too):

 cloning Repo
 Cloning into '/repo'...
 changing directory

I'm not getting any errors so diagnosing what's going on is posing to be the problem for me. Any help is appreciated!


Solution

  • Because you're using >>log.txt on each command, that log file is being re-opened for every command -- meaning that using cd changes the directory in which that logfile is being created.

    To fix this, at the top of your script, use:

    exec 3>log.txt
    

    ...and, whenever you want to write to that file, append >&3 to each command to write to that previously-opened file descriptor.