0

I have a shell script and I want to use it for making directories and files in those direcctories. It is extremely important that this script does not overwrite or delete any files or directories. So I want to make a directory which is one directory above from the directory where the script is in. In this directory I want to make two subdirectories and in one of the subdirectories I want to copy 2 pre-existing files that have some text in them.

Files file1 and file2 are always going to be in same directory as this script and they always have same contents in them and it is very important that the contents do not change. I have multiple structures like this, they just have different names.

So I tried this:

#! /bin/bash

echo "Enter directory name"
read dirname

mkdir -p ../$dirname/{dir1,dir2}
cp file1 file2 ../$dirname/dir2

But if dirname already exists, this script overwrites it and also overwrites all the contents in it. Then I tried this:

#! /bin/bash

echo "Enter directory name"
read dirname

if [ -d $dirname ]
then
    echo "directory already exists"
else
    mkdir -p ../$dirname/{dir1,dir2}
    cp file1 file2 ../$dirname/dir2
fi

But also this script overwrites everything. How can I make this script so that if dirname already exists, the script does not create new directories and it does not copy any files in any directory, i.e. it does not do anything?

Programmer
  • 306
  • 2
  • 8
  • Shouldn't the directory check be `-d "../$dirname"`? – Inian Jun 11 '20 at 15:01
  • I think that unless you provide a full path in ```dirname```, this won't work.. You have to change your test to ```[ -d ../$dirname ]``` to test the path relatively to your script – cocool97 Jun 11 '20 at 15:17
  • 1
    Agree with the above. Also, when using a relative path like this, you may want to get the absolute location of the script using this method: https://stackoverflow.com/a/246128/4158311. Then the user doesn't need to be in the same directory as the script to run it. – John Moon Jun 11 '20 at 15:26

0 Answers0