Run BASH script in Cygwin

0

Installed cygwin, wrote my script, tested successfully. However when I go to run it as a Windows scheduled task it fails. Further digging is showing that not all programs are available when running the script in this manner. For example Launching Mintty and typing in ls will list the contents of my directory. Running bash.exe from the windows CLI will put me in a "BASH" prompt, but ls is not a recognized command.

I have tried the standard

c:\cygwin\bin\bash.exe -l -c "/home/user/logoff.sh"

as well as the

c:\cygwin\bin\mintty.exe /bin/bash -l -c "/home/user/logoff.sh"

I added an echo command that outputs to a text file, and that works so I know the script is getting called. The issue appears to either be with the various programs not being available, or it doesn't like the piping I am doing.

This is the script I am trying to run.

for user in user1 user2 user3 ;
do
id=$(query user $user 2>> /dev/null | awk '{ print $3 }' | sed -e '/ID/ d')
if [[ "$id" =~ ^[1-9][0-9]?$ ]]; then
logoff $id
echo "$user was logged off" >> logg_off.log
fi
done

Any ideas?

EDIT

  1. I fat fingered the file name in the scheduled task, which is why it failed to run.
  2. Still not sure why the script would fail to finish. I removed all but one user from the list and everything works as expected. Will have to wait until this evening to test whether or not I can log off the other users in one pass.

TurboAAA

Posted 2017-03-08T14:52:05.173

Reputation: 11

try using the applications full paths in the script /usr/bin/awk and so on – Nifle – 2017-03-08T14:56:09.637

When debugging, try to break down the script line by line to find the problem. You should be able to pinpoint the problem to a single line and go from there. – mtak – 2017-03-08T15:02:59.787

Try escaping the $

– DavidPostill – 2017-03-08T15:16:44.393

Those are good steps to take. Will need to remember that the path may not include awk, grep, sed, etc and need to specify their locations. – TurboAAA – 2017-03-08T15:38:46.747

Answers

0

So after some more fiddling around I found that the session ID is removed when the user is disconnected. Instead of inserting a tab or similar as a place holder, it just inserts spaces. So when AWK prints out the column is prints the wrong information. Below is the final script that runs as a scheduled job in Windows Server.

for user in user1 user2 user3 ;
do
id=$(query user $user 2>> /dev/null | awk '{ print $3 }' | sed -e '/ID/ d')
if [[ "$id" =~ ^[1-9][0-9]?$ ]]; then
logoff $id
date >> /cygdrive/c/log_off.log
echo "$user was logged off" >> /cygdrive/c/log_off.log
else
id2=$(query user $user 2>> /dev/null | awk '{ print $2 }' | sed -e '/SESSIONNAME/ d')
if [[ "$id2" =~ ^[1-9][0-9]?$ ]]; then
logoff $id2
date >> /cygdrive/c/log_off.log
echo "$user was logged off" >> /cygdrive/c/log_off.log
fi
fi
done

TurboAAA

Posted 2017-03-08T14:52:05.173

Reputation: 11