In: Computer Science
Examine the following shell script and describe its function line-by-line:
#!/bin/bash
echo -e "Which file would you like to copy> --> \c"
echo -e "Which file would you like to copy? --> \c?"
read FILENAME
mkdir /stuff || echo "The /stuff directory could not be created." && echo "The /stuff directory could not be created."
cp -f $FILENAME /stuff && echo "$FILENAME was successfully copied to /stuff"
echo -e "Which file would you like to copy> --> \c"
This line prints out Which file would you like to copy> -->.
The \c is used to supress new line character so that the next echo statement also prints on same line.
The next line echo -e "Which file would you like to copy? --> \c?" also echos-
Which file would you like to copy? -->
Again, the \c is used to supress newline, so that the next statement will start in the same line.
read FILENAME
this line takes input , and stores the input in the variable called FILENAME.
The next line-
mkdir /stuff || echo "The /stuff directory could not be created." && echo "The /stuff directory could not be created."
This first tries to make the directory stuff in the home directory (mkdir command is used to create directories).
The || is used for piping, that is if the first statement (mkdir /stuff) returns false i.e if the mkdir command fails, the next command is executed, where the line echo "The /stuff directory could not be created"
will be executed twice due to the presence of &&.
mkdir can fail if the shell script does not have appropriate permissions.
The last line tries to copy the file stored in the FILENAME variable to the stuff directory which has been created previously. If the copy successfully passes, only then do we move on to the next statement after && which is
echo "$FILENAME was successfully copied to /stuff".
If for any reason we have provided a FILENAME which does not exist or the /stuff directory was not created , the error will be printed and the next echo statement will not be executed as the first statement returns false.
So all in all the script asks us to enter a FILENAME, and tries to copy the file to the /stuff directory.