John Bailey
John Bailey

Reputation: 11

Parts of Bash function don't execute on Linux

I am trying to write a script that will sit on my machine and listen for a file in a specific folder, then run a function to start an application. In the code below everything executes except the line "java -jar Minecraft.jar" and I am unsure why. I am not getting an error. I see the notification from the Notify statement. If anyone else could give me some direction I would greatly appreciate it.

Thank you

Code:

#!/bin/bash

Launch_Minecraft () {
echo "Starting Minecraft..." 
cd .. &
cd Games &
cd Minecraft &
notify-send "Starting Minecraft"
java -jar Minecraft.jar & 
rm /home/MyFolder/Dropbox/Alexa/launchminecraft.txt &
cd /home/MyFolder/Desktop
}

for (( ; ; ))
do
   [ -f /home/MyFolder/Dropbox/Alexa/launchminecraft.txt ] && Launch_Minecraft|| echo "Listening... [ hit CTRL+C to stop]"
done

Upvotes: 1

Views: 58

Answers (2)

cxw
cxw

Reputation: 17051

codeforester is right - & in bash doesn't mean "and do this next," but rather "move on to the next command without waiting." Remove the trailing & from all lines except the java line and you should have more luck.

Other thoughts:

  • for ((;;)) can be replaced by while : or while true.
  • use [[ ]] instead of [ ] for tests - bash has its own built-in tests.
  • x && y || z can have unexpected behaviour if y fails.* Instead, try:

    while true
    do
        echo "Listening... [ hit CTRL+C to stop]"
        [[ -f /home/MyFolder/Dropbox/Alexa/launchminecraft.txt ]] && Launch_Minecraft
        sleep 1   # or something to prevent this script from eating all your CPU cycles!
    done
    

* Note: In x && y || z, if x succeeds and y fails, z will be executed, which may not be what you think would happen. E.g., true && false || echo n prints n even though x (true) succeeded.

Upvotes: 2

codeforester
codeforester

Reputation: 43089

Why are you executing all the commands in the background with &? That seems like the issue.

Upvotes: 1

Related Questions