Reputation: 33
I'm taking a basic operating systems class and have been given an assignment as follows: "Write a shell script that moves a file from the current folder to a sub-folder known as Backup. It should accept the source and destination as arguments to the script. The script should display an error if the user does not key in two arguments, or if the file was not found or if a different user (other than yourself) attempts to execute the script."
I've written a script as follows:
if [ $# -eq 2 ]; then
if ! [[ -f "$1" ]]; then
echo Error: The file $1 was not found.
exit 1
fi
else
echo Error: Check syntax or number of arguments
echo Correct use: $0 [source] [destination]
exit 1
fi
echo Copying file $1 to $2/backup/$1
mkdir $2
mkdir $2/backup
cp $1 $2/backup
I've tested this on Cygwin on W7 since I don't have access to a linux environment at the moment (we usually SSH into a remote server but it's down for some reason) and it works for the first two requirements of checking the number of arguments passed and the file not found. I've done some searching but unfortunately I'm absolutely clueless as to how to do the last part that restricts the user execution - that's where I need help.
I'm much more interested in learning how it's done and why it's done that way as opposed to the code itself, so I would greatly appreciate extensive explanation if possible.
Thanks
Upvotes: 1
Views: 3975
Reputation: 1
Isn't the obvious thing to do just to use file permissions? Make the script be owned by whichever user you want to be able to run it, and set the permissions to 0700.
If the script is supposed to figure out which user is running it, then use "id -u -n".
Upvotes: 0
Reputation: 44
You could use the environmental variable $USER to check against your own username
if [ "$USER" != "allowed_username" ]; then
echo 'Access denied'
exit 1
fi
Upvotes: 2