0

I'm fairly new to bash scripting. I'm trying to create a directory with a timestamp and then cd into the directory. I'm able to create a directory and can cd into it the directory with one command.

mkdir "build" && cd "build"

I can create the directory with data then cd into it.

mkdir date '+%m%d%y' && cd date '+%m%d%y' I am able to create this dir and cd into it with one command.

Here is my bash script:

#!/bin/bash

# mkdir $(date +%F) && cd $(date +%F)

 mkdir build_`date '+%m%d%y'` && cd build_`date '+%m%d%y'`

I need to create the directory with build_date '+%m%d%y' in the title then cd into that folder. I've looked online but am unable to come up with a solution.

Thank you.

larsks
  • 277,717
  • 41
  • 399
  • 399

3 Answers3

0

Try this:

#!/bin/bash

build_dir="build_$(date '+%m%d%y')"

mkdir $build_dir && cd $build_dir
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

Best is to name your Folders YYYY.MM.DD like build_2019.11.21

#!/bin/bash
DIRECTORY="build_$(date '+%Y.%m.%d')"
if [ ! -d "$DIRECTORY" ]; then
    # checking if $DIRECTORY doesn't exist.
    mkdir $DIRECTORY
fi
cd $DIRECTORY
touch testfile
0

Here's a script that uses /usr/bin/env bash and the builtin command printf instead of /bin/date.

#!/usr/bin/env bash

date="$(printf '%(%m%d%y)T' -1)"
[[ -d build_"${date}" ]] || mkdir build_"${date}"
cd build_"${date}"

# do something useful here
# ...

However, changing directory in a script (subshell) is not much use on its own, as your current working directory ($PWD) will be the same after the script exits.

If you want to have the current shell session change into the new directory, use a shell function.

mkbuild() {
  date="$(printf '%(%m%d%y)T' -1)"
  [[ -d build_"${date}" ]] || mkdir build_"${date}"
  cd build_"${date}"
}

Then run it:

$ echo $PWD
/tmp
$ mkbuild
$ echo $PWD
/tmp/build_112119