How to "cd" to a directory which is created using "mkdir $(date '+%d-%b-%Y')" - bash

mkdir $(date '+%d-%b-%Y')
then cd to the dynamically created directory
How to "cd" to a directory which is created using "mkdir $(date '+%d-%b-%Y')" and do the operations by moving into the created directory in bash script

Simple way would be, you store the directory name in a variable
dirname=$(date '+%d-%b-%Y')
if [ -n "$dirname" ]; then
mkdir "$dirname"
if [ -d "$dirname" ]; then
cd "$dirname"
fi
fi
Added some error handling and also if your file is written in Windows and being run in an unix environment or vice-versa, I would recommend using dos2unix which will handle the new line character conversions (this is for the ? characters OP is seeing in ls).

Can you show me your case?
In most cases, you should not cd in to the directory. Use absolute path instead:
Good practice:
mkdir /tmp/mydir/
cp -R /usr/local/example/ /tmp/mydir/
sed 's/foo/bar/g' /tmp/mydir/afile
Bad practice:
mkdir /tmp/mydir/
cd /tmp/mydir/
cp -R /usr/local/example/ .
sed 's/foor/bar/g' afile
P.S.
Subj:
$ mkdir $(date '+%d-%b-%Y')
$ cd $(date '+%d-%b-%Y')
$ pwd
/Users/user/18-Feb-2019

In Bash, $_ expands to the last argument to the previous command. So you could do:
mkdir $(date '+%d-%b-%Y')
cd $_
In a real Bash program you would want to quote the expansions (use Shellcheck on your code to check for missing quotes), and check for errors on both mkdir and cd.

Related

trying to create a script with timestamp [duplicate]

This question already has answers here:
Why can't I change directories using "cd" in a script?
(33 answers)
Closed 3 years ago.
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.
Try this:
#!/bin/bash
build_dir="build_$(date '+%m%d%y')"
mkdir $build_dir && cd $build_dir
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
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

Bash relative path to absolute path [duplicate]

I have written a Bash script that takes an input file as an argument and reads it.
This file contains some paths (relative to its location) to other files.
I would like the script to go to the folder containing the input file, to execute further commands.
In Linux, how do I get the folder (and just the folder) from an input file?
To get the full path use:
readlink -f relative/path/to/file
To get the directory of a file:
dirname relative/path/to/file
You can also combine the two:
dirname $(readlink -f relative/path/to/file)
If readlink -f is not available on your system you can use this*:
function myreadlink() {
(
cd "$(dirname $1)" # or cd "${1%/*}"
echo "$PWD/$(basename $1)" # or echo "$PWD/${1##*/}"
)
}
Note that if you only need to move to a directory of a file specified as a relative path, you don't need to know the absolute path, a relative path is perfectly legal, so just use:
cd $(dirname relative/path/to/file)
if you wish to go back (while the script is running) to the original path, use pushd instead of cd, and popd when you are done.
* While myreadlink above is good enough in the context of this question, it has some limitation relative to the readlink tool suggested above. For example it doesn't correctly follow a link to a file with different basename.
Take a look at realpath which is available on GNU/Linux, FreeBSD and NetBSD, but not OpenBSD 6.8. I use something like:
CONTAININGDIR=$(realpath ${FILEPATH%/*})
to do what it sounds like you're trying to do.
This will work for both file and folder:
absPath(){
if [[ -d "$1" ]]; then
cd "$1"
echo "$(pwd -P)"
else
cd "$(dirname "$1")"
echo "$(pwd -P)/$(basename "$1")"
fi
}
$cat abs.sh
#!/bin/bash
echo "$(cd "$(dirname "$1")"; pwd -P)"
Some explanations:
This script get relative path as argument "$1"
Then we get dirname part of that path (you can pass either dir or file to this script): dirname "$1"
Then we cd "$(dirname "$1"); into this relative dir
pwd -P and get absolute path. The -P option will avoid symlinks
As final step we echo it
Then run your script:
abs.sh your_file.txt
Try our new Bash library product realpath-lib over at GitHub that we have given to the community for free and unencumbered use. It's clean, simple and well documented so it's great to learn from. You can do:
get_realpath <absolute|relative|symlink|local file path>
This function is the core of the library:
if [[ -f "$1" ]]
then
# file *must* exist
if cd "$(echo "${1%/*}")" &>/dev/null
then
# file *may* not be local
# exception is ./file.ext
# try 'cd .; cd -;' *works!*
local tmppwd="$PWD"
cd - &>/dev/null
else
# file *must* be local
local tmppwd="$PWD"
fi
else
# file *cannot* exist
return 1 # failure
fi
# reassemble realpath
echo "$tmppwd"/"${1##*/}"
return 0 # success
}
It's Bash 4+, does not require any dependencies and also provides get_dirname, get_filename, get_stemname and validate_path.
Problem with the above answer comes with files input with "./" like "./my-file.txt"
Workaround (of many):
myfile="./somefile.txt"
FOLDER="$(dirname $(readlink -f "${ARG}"))"
echo ${FOLDER}
I have been using readlink -f works on linux
so
FULL_PATH=$(readlink -f filename)
DIR=$(dirname $FULL_PATH)
PWD=$(pwd)
cd $DIR
#<do more work>
cd $PWD

Bash script - File directory does not exist

I'm creating a very simple bash script that will check to see if the directory exists, and if it doesn't, create one.
However, no matter what directory I put in it doesn't find it!
Please tell me what I'm doing wrong.
Here is my script.
#!/bin/bash
$1="/media/student/System"
if [ ! -d $1 ]
then
mkdir $1
fi
Here is the command line error:
./test1.sh: line 2: =/media/student/System: No such file or directory
Try this
#!/bin/bash
directory="/media/student/System"
if [ ! -d "${directory}" ]
then
mkdir "${directory}"
fi
or even shorter with the parent argument of mkdir (manpage of mkdir)
#!/bin/bash
directory="/media/student/System"
mkdir -p "${directory}"
In bash you are not allow to start a variable with a number or a symbol except for an underscore _. In your code you used $1 , what you did there was trying to assign "/media/student/System" to $1, i think maybe you misunderstood how arguments in bash work. I think this is what you want
#!/bin/bash
directory="$1" # you have to quote to avoid white space splitting
if [[ ! -d "${directory}" ]];then
mkdir "$directory"
fi
run the script like this
$ chmod +x create_dir.sh
$ ./create_dir.sh "/media/student/System"
What the piece of code does is to check if the "/media/student/System" is a directory, if it is not a directory it creates the directory

BASH redirect create folder

How can I have the following command
echo "something" > "$f"
where $f will be something like folder/file.txt create the folder folder if does not exist?
If I can't do that, how can I have a script duplicate all folders (without contents) in directory 'a' to directory 'b'?
e.g if I have
a/f1/
a/f2/
a/f3/
I want to have
b/f1/
b/f2/
b/f3/
The other answers here are using the external command dirname. This can be done without calling an external utility.
mkdir -p "${f%/*}"
You can also check if the directory already exists, but this not really required with mkdir -p:
mydir="${f%/*}"
[[ -d $mydir ]] || mkdir -p "$mydir"
echo "something" | install -D /dev/stdin $f
try
mkdir -p `dirname $f` && echo "something" > $f
You can use mkdir -p to create the folder before writing to the file:
mkdir -p "$(dirname $f)"

How to mkdir only if a directory does not already exist?

I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the mkdir command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that mkdir throws when it tries to create an existing directory.
How can I best do this?
Try mkdir -p:
mkdir -p foo
Note that this will also create any intermediate directories that don't exist; for instance,
mkdir -p foo/bar/baz
will create directories foo, foo/bar, and foo/bar/baz if they don't exist.
Some implementation like GNU mkdir include mkdir --parents as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.
If you want an error when parent directories don't exist, and want to create the directory if it doesn't exist, then you can test for the existence of the directory first:
[ -d foo ] || mkdir foo
This should work:
$ mkdir -p dir
or:
if [[ ! -e $dir ]]; then
mkdir $dir
elif [[ ! -d $dir ]]; then
echo "$dir already exists but is not a directory" 1>&2
fi
which will create the directory if it doesn't exist, but warn you if the name of the directory you're trying to create is already in use by something other than a directory.
Use the -p flag.
man mkdir
mkdir -p foo
Defining complex directory trees with one command
mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}
If you don't want to show any error message:
[ -d newdir ] || mkdir newdir
If you want to show your own error message:
[ -d newdir ] && echo "Directory Exists" || mkdir newdir
mkdir foo works even if the directory exists.
To make it work only if the directory named "foo" does not exist, try using the -p flag.
Example:
mkdir -p foo
This will create the directory named "foo" only if it does not exist. :)
The old tried and true
mkdir /tmp/qq >/dev/null 2>&1
will do what you want with none of the race conditions many of the other solutions have.
Sometimes the simplest (and ugliest) solutions are the best.
Simple, silent and deadly:
mkdir -p /my/new/dir >/dev/null 2>&1
You can either use an if statement to check if the directory exists or not. If it does not exits, then create the directory.
dir=/home/dir_name
if [ ! -d $dir ]
then
mkdir $dir
else
echo "Directory exists"
fi
You can directory use mkdir with -p option to create a directory. It will check if the directory is not available it will.
mkdir -p $dir
mkdir -p also allows to create the tree structure of the directory. If you want to create the parent and child directories using same command, can opt mkdir -p
mkdir -p /home/parent_dir /home/parent_dir/child1 /home/parent_dir/child2
mkdir does not support -p switch anymore on Windows 8+ systems.
You can use this:
IF NOT EXIST dir_name MKDIR dir_name
directory_name = "foo"
if [ -d $directory_name ]
then
echo "Directory already exists"
else
mkdir $directory_name
fi
This is a simple function (Bash shell) which lets you create a directory if it doesn't exist.
#------------------------------------------#
# Create a directory if it does not exist. #
#------------------------------------------#
# Note the "-p" option in the mkdir #
# command which creates directories #
# recursively. #
#------------------------------------------#
createDirectory() {
mkdir -p -- "$1"
}
You can call the above function as:
createDirectory "$(mktemp -d dir-example.XXXXX)/fooDir/BarDir"
The above creates fooDir and BarDir if they don't exist. Note the "-p" option in the mkdir command which creates directories recursively.
Referring to man page man mkdir for option -p
-p, --parents
no error if existing, make parent directories as needed
which will create all directories in a given path, if exists throws no error otherwise it creates all directories from left to right in the given path. Try the below command. the directories newdir and anotherdir doesn't exists before issuing this command
Correct Usage
mkdir -p /tmp/newdir/anotherdir
After executing the command you can see newdir and anotherdir created under /tmp. You can issue this command as many times you want, the command always have exit(0). Due to this reason most people use this command in shell scripts before using those actual paths.
Or if you want to check for existence first:
if [[ ! -e /path/to/newdir ]]; then
mkdir /path/to/newdir
fi
-e is the exist test for KornShell.
You can also try googling a KornShell manual.
Improvement on the 'classic' solution (by Brian Campbell) - to handle the case of symlink to a directory.
[ -d foo/. ] || mkdir foo
mkdir -p sam
mkdir = Make Directory
-p = --parents
(no error if existing, make parent directories as needed)
if [ !-d $dirName ];then
if ! mkdir $dirName; then # Shorter version. Shell will complain if you put braces here though
echo "Can't make dir: $dirName"
fi
fi

Resources