I am new to bash and am attempting to take in 2 arguments, and Argument 1 is the name of the new directory where the copied file will go. Argument 2 is the file to be copied. Argument 3 is the name of the new file. However, I keep getting the mkdir missing operand error message when running it. Thank you for any help!!
#!/bin/bash
dir=$1
oldFile=$2
newFile=$3
mkdir $dir
cp $2 $dir
cd $dir
mv $2 $3
BRAND NEW, this version covers all cases...
#!/bin/bash
# Verify number of arguments
if [[ $# -ne 3 ]]
then
echo "Missing arguments."
echo "1: new directory name"
echo "2: existing file to copy in the directory"
echo "3: new filename"
exit 1
fi
# Verify arguments values
dir="$1"
if [[ -d "$dir" ]]
then
echo "Directory $dir already exists. Cannot proceed."
exit 2
fi
oldfile="$2"
if [[ ! -f "$oldfile" ]]
then
echo "The second arguments must be an existing file. Cannot procees."
exit 3
fi
newfile="$3"
# no check to do here.
# Create the directory
mkdir "$dir"
if [[ ! -d "$dir" ]]
then
echo "ERROR: directory $dir could not be created. Aborting."
exit 4
else
echo "INFO: created directory $dir"
fi
# Copy the file into the directory, with the new name
cp "$oldfile" "$dir/$newfile"
if [[ ! -f "$dir/$newfile" ]]
then
echo "ERROR: the existing file ($oldfile) could not be copied and renamed ($newfile)."
exit 5
else
echo "INFO: the existing file ($oldfile) was copied and renamed ($newfile) in the $dir directory."
fi
This script:
Remember to:
"
your variablesrm
, mv
, you can loose things if you have an unexpected behavior.To call the script:
./thescript.bash newdirectory oldfilename newfilename
It will give you the files-directory structure:
$ ls
oldfile
newdirectory/newfilename