mercredi 19 octobre 2016

bash - file test check always returns true if run with sudo

I'm a bit stumped, I have a bash script I'm looking to use to 'setup' my project I'm working. It contains if then else statements but a section that writes a sym link to /etc/cron.hourly/ and therefor needs sudo to complete this part. My issue is; when I run the command with sudo ./script it will always return true for my first check for a directory. If I don't run the script with sudo then the later section which add's the sym link fails. Can someone please advise a way around this? Here's an example of my code, excuse some of the commends I've used them at the beginning to plan my layout: Be gentle - this is my first project in BASH lol

#!/bin/bash
clear
echo "project - Setup"
cdir=$(pwd)
#wd=~/project/project-wd/
echo "Current dir is $cdir"
#Look for project-wd in ~/project
echo "Looking for project-wd"
if [ -d ~/project/project-wd ];
then
    echo "project-wd already exists!"
else
    echo "project-wd not detected - creating"
    mkdir ~/project
    if
    [ -d ~/project ]
    then
        echo "project directory successfully ceated!"
    else
        echo "NOTICE:  Failed to create ~/project/"
    fi
    echo "Copying project-wd to Home..."
    cp -r $cdir/project-wd/ ~/project/
    if [ -d ~/project/project-wd ]
    then
        echo "project-wd created successfully!"
    else
        echo "NOTICE:  Failed to copy project-wd to Home!"
        echo "Try re-running the script with sudo"
    fi
fi
#Add worker instance to cron.d
#echo $wd/project-worker.sh >> /etc/cron.hourly
if [ -f /etc/cron.hourly/project-worker.sh ]
then
    echo "project-worker.sh (symbolic link) detected!"
    echo "NOTICE:  project setup completed successfully!"
else
    echo "Could not detect 'project-worker.sh (sym link) in /etc/cron.hourly/"
    echo "Adding project-worker to cron..."
    echo "NOTE:  This will fail if you haven't run the script with elevated privileges eg. $sudo setup-project.sh"
    ln -s ~/project/project-wd/project-worker.sh /etc/cron.hourly/project-worker.sh
    if [ -f /etc/cron.hourly/pincheck-worker.sh ]
    then
        echo "DETECTED:  project-worker.sh in /etc/cron.hourly/"
        echo "project-worker.sh symbolic link was successfully created!"
        echo "NOTICE:  project setup successful!"
    else
        echo "NOTICE:  project-worker.sh not detected in /etc/cron.hourly/"
        echo "Worker script will not run monitor scripts for your jobs"
        echo "NOTICE:  project setup failed!"
    fi
fi
exit

Aucun commentaire:

Enregistrer un commentaire