简体   繁体   中英

How to restrict execution of a bash script to a specific user

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

You could use the environmental variable $USER to check against your own username

if [ "$USER" != "allowed_username" ]; then
  echo 'Access denied'
  exit 1
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM