Search code examples
linuxshellshmkdir

Linux shell file. mkdir and pushd commands not doing what I'd like


I'm trying to create a directory if it does not exist, and the further down the line, create a log file in that directory. It would be in the current users home directory
In pseudocode:

If directory "/home/LOGS" does not exist
make directory "/home/LOGS"

Then whenever a log file is created, it will save in that directory, not the directory that the program is being run from.
This is what I have so far, and it's just not working...

pushd -n  $"../LOGS" >/dev/null 2>&1 

#Create the logs folder
if [ ! -d $"home/LOGS" ]; then
 mkdir -p $"home/LOGS"
fi 

If it helps, my files are being saved like so:

     function savefile {
# Save to file
  if [ -e $username.log ]; then
    echo "Username already exists, returning you to the menu."
    sleep 2
    clear
      menu
  else
    echo $fullname >> $username.log
    echo $password >> $username.log
      curdate=$(date +'%d/%m/%Y %H:%M:%S')
    echo $curdate >> $username.log
  echo "Creating your account"
    sleep 2
    clear
  echo "Account created"
  echo
    afterBasic
  fi 
}

Any help would be greatly appreciated.


Solution

  • mkdir -p by itself provides the logic you want, so you could simply do:

    mkdir -p "$HOME/LOGS" && pushd "$HOME/LOGS" >/dev/null || exit
    
    • mkdir -p creates the target directory if it doesn't already exists and then changes to it.
      • Note that mkdir -p indicates success even if the target already exists.
      • This allows unconditional use of mkdir -p, without having to worry about whether the directory already exists or not.
    • && pushd "$HOME/LOGS" >/dev/null then changes to directory "$HOME/LOGS", suppressing its usual stdout output (>/dev/null)
      • Note that stderr output, unlike in your code, is deliberately not suppressed so that error messages don't get lost.
    • To be safe, || exit exits the script with a nonzero exit code (to signal failure), if the directory couldn't be created or changed to (because the exit command here doesn't explicitly specify an exit code, the previous command's exit code is passed through - which, in this case, is nonzero by definition).

    Note that I've used "$HOME/LOGS", assuming that's what you really want; i.e., a LOGS subdirectory in the current user's home directory.

    If instead you want absolute path /home/LOGS, just drop the $ from your original string.

    $"home/LOGS" will by default evaluate to home/LOGS, i.e., a relative path. The rarely used $"..." strings are meant for use in localization.