# Using the Foreach loop, Needing help

**URL:** <https://community.unix.com/t/using-the-foreach-loop-needing-help/297249>\
**Category:** UNIX for Dummies Questions & Answers\
**Created:** [October 14, 2011, 3:35pm UTC](https://community.unix.com/t/using-the-foreach-loop-needing-help/297249 "2011-10-14T15:35:16Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![grahamn95](https://community.unix.com/user_avatar/community.unix.com/grahamn95/32/7428_2.png) [@grahamn95](https://community.unix.com/u/grahamn95)\
**Post date:** [October 14, 2011, 3:35pm UTC](https://community.unix.com/t/using-the-foreach-loop-needing-help/297249/1 "2011-10-14T15:35:16Z")

</div>

I am trying to make a script for my Counter-Strike: Source servers. What i am wanting it to do is for it to restart each server, the only way i can think of doing this in through for each.

Years what i have at the moment.

```nohighlight
server_start() {
	START=`ps x | grep SCREEN | grep $SRV | cut -d '?' -f 1`
		if [! -n "$START"]; then
            echo -e "${txtgrn}${txtbld}$SRV is starting up${txtrst}"
			if [$SRV = "minecraft"]; then
				cd $SRV
                                ./$SRV.sh
                                cd
			else
				cd $SRV/css
                                ./$SRV.sh
                                cd
			fi
		else
            echo -e "${txtred}${txtbld}Error: $SRV is already running!${txtrst}"
		fi
}

```

What this does, the user would enter in this command to start up a server

```nohighlight
./tmf.sh start jailbreak

```

I am looking for a way to stop / start / update them all at once using one command.

Also i am a bit of noob when it comes to bash so tips and examples would be helpful

---

<div class="post-metadata">

**Author:** ![Corona688](https://community.unix.com/letter_avatar/corona688/32/6_449c533f586939b6e5f246632a46421f.png) [@Corona688](https://community.unix.com/u/Corona688)\
**Post date:** [October 14, 2011, 3:53pm UTC](https://community.unix.com/t/using-the-foreach-loop-needing-help/297249/2 "2011-10-14T15:53:10Z")

</div>

There must be more to that script. You use lots of variables you never defined, and a function doesn't call itself.

An explanation of why you're grepping for SCREEN would be good.

The contents of this $SRV.sh would be good to see too.

If you save the PID's of the servers you're running, you won't have to use `ps | awk | grep | cut | sed | kitchen | sink` to see if they're running -- just check the PID. Much simpler and more reliable. How to do that depends on how they're run in the first place...

Do you have the start-stop-daemon command available?

---------- Post updated at 01:53 PM ---------- Previous update was at 01:47 PM ----------

If these are all folders...

```nohighlight
cd /path/to/folder
for SERVICE in *
do
        command SERVICE
done

```

---

<div class="post-metadata">

**Author:** ![grahamn95](https://community.unix.com/user_avatar/community.unix.com/grahamn95/32/7428_2.png) [@grahamn95](https://community.unix.com/u/grahamn95)\
**Post date:** [October 14, 2011, 4:04pm UTC](https://community.unix.com/t/using-the-foreach-loop-needing-help/297249/3 "2011-10-14T16:04:09Z")

</div>

He is the script in full.

```nohighlight
#!/bin/bash

#Script - Functions
NO_ARGS=0
CMD=$1
SRV=$2

# Text color variables
txtund=$(tput sgr 0 1) # Underline
txtbld=$(tput bold) # Bold
txtred=$(tput setaf 1) # Red
txtgrn=$(tput setaf 2) # Green
txtylw=$(tput setaf 3) # Yellow
txtblu=$(tput setaf 4) # Blue
txtpur=$(tput setaf 5) # Purple
txtcyn=$(tput setaf 6) # Cyan
txtwht=$(tput setaf 7) # White
txtrst=$(tput sgr0) # Text reset

txtund=$(tput sgr 0 1) # Underline
txtbld=$(tput bold) # Bold

#Counter-Strike: Source - Functions

#Minecraft - Functions
UpdateURL=http://ci.bukkit.org/job/dev-CraftBukkit/Recommended/artifact/target/craftbukkit-0.0.1-SNAPSHOT.jar

#Backup - Functions
files=minecraft/world
ext=.tar.gz
parameters=zcvf

hdateformat=$(date '+%d-%m-%Y-%H-%M')H$ext

backupdir=minecraft/backups
expire=3

#Global - Functions

#If the user inputted the detials incorrectly
usage() {
    echo "Usage of the TmF Engine Script"
    echo "./tmf.sh $FUNC {Server}"
}

#Single Startup
server_start() {
	START=`ps x | grep SCREEN | grep $SRV | cut -d '?' -f 1`
		if [! -n "$START"]; then
            echo -e "${txtgrn}${txtbld}$SRV is starting up${txtrst}"
			if [$SRV = "minecraft"]; then
				cd $SRV
                ./$SRV.sh
                cd
			else
				cd $SRV/css
                ./$SRV.sh
                cd
			fi
		else
            echo -e "${txtred}${txtbld}Error: $SRV is already running!${txtrst}"
		fi
}

#Single Stop
server_stop() {
STOP=`ps x | grep SCREEN | grep $SRV | cut -d '?' -f 1`
    if ["$(screen -ls | grep $SRV)" == ""] ; then
        echo -e "${txtred}${txtbld}Error: $SRV is not running!${txtrst}"
    else
        if [$SRV = "minecraft"]; then
            screen -x minecraft -p 0 -X stuff "Server shutting down$(echo -ne '\r')"
            screen -x minecraft -p 0 -X stuff "stop$(echo -ne '\r')"
            rm -R minecraft/server.log
            rm -R minecraft/worldedit.log
            cd
            echo -e "${txtgrn}${txtbld}$SRV is now offline${txtrst}"
        else
            sleep 5
            screen -dr $STOP -X quit
            echo -e "${txtgrn}${txtbld}$SRV is now offline${txtrst}"
        fi
    fi
}

#Update Check - Updates the correct server with the right parameters
server_update() {
    if [$SRV = "minecraft"]; then
        echo -e "${txtblu}${txtbld}Prompting users that update is incoming. Waiting for 60secs${txtrst}"
        screen -x minecraft -p 0 -X stuff "say Going down for an update in 60 seconds.$(echo -ne '\r')"
        sleep 55
        screen -x minecraft -p 0 -X stuff "say Going down for an update in 5 seconds.$(echo -ne '\r')"
        sleep 5
        screen -x minecraft -p 0 -X stuff "stop$(echo -ne '\r')"
        sleep 5
        server_update_MINECRAFT
    else
        server_stop
        sleep 5
        server_update_CSS
    fi
}

#Minecraft Update - Function
server_update_MINECRAFT() {
    PRC=`ps x | grep $PRC | grep -v grep | cut -d '?' -f 1`
    STILLRUN=`ps x | grep $PRC | grep -v grep | cut -d '?' -f 1`
        if ["$STILLRUN" = "$PRC"]; then
            echo -e "${txtred}${txtbld}Error: $SRV was unable to shutdown!${txtrst}"
            exit
        else
            cd minecraft
            wget -N $UpdateURL
            cd
            echo -e "${txtgrn}${txtbld}$SRV has been updated successfully${txtrst}"
        fi
}

#Counter-Strike: Source update function
server_update_CSS() {
    PRC=`ps x | grep SCREEN | grep $SRV | cut -d '?' -f 1`
        if [! -n "$PRC"]; then
            PRC=999999999999
        else
            kill -9 $PRC
            echo -e "${txtgrn}${txtbld}$SRV has been successfully shutdown${txtrst}"
        fi
    STILLRUN=`ps x | grep $PRC | grep -v grep | cut -d '?' -f 1`
        if ["$STILLRUN" = "$PRC"]; then
            echo -e "${txtred}${txtbld}Error: $SRV was unable to shutdown!${txtrst}"
            exit
        else
            echo "Updating $SRV now"
            if [[$SRV = 'badwater' || $SRV = 'controlpoint']]; then
				/home/server/1hldsupdatetool/./steam -command update -game tf -dir "/home/server/$SRV"
			else
				/home/server/1hldsupdatetool/./steam -command update -game "counter-strike source" -dir "/home/server/$SRV"
			fi
			echo -e "${txtgrn}${txtbld}$SRV has been updated successfully${txtrst}"
			server_start
		fi
}

#Single Restart
server_restart() {
    server_stop
    sleep 10
    server_start
}

#Minecraft Backup - Function
server_minecraft_backup() {
        #Does the backup folder exist if not create it
    if [-d $BackupDIR]; then
        sleep 0
    else
        mkdir -p $BackupDIR
    fi

    #is the server online, if not dont backup
    if ["$(screen -ls | grep minecraft)" == ""] ; then
        exit
    else
        #Minecraft Server messages (Backup Starting and stopping world saving)
        screen -x minecraft -p 0 -X stuff "say Backup Started, Saving turned off.$(echo -ne '\r')"
        screen -x minecraft -p 0 -X stuff "save-off$(echo -ne '\r')"
        
        #Compressions or the Files
        tar $parameters $hdateformat $files
        
        #Move compressed files to the backups folder
        mv $hdateformat $backupdir
        
        #Remove old backups
        find $backupdir/ -name *H$ext -mtime +$expire -exec rm {} \;
        
        #Minecraft Server messages (Backup Finished and starting world saving)
        screen -x minecraft -p 0 -X stuff "say Backup Finished, Saving turned on.$(echo -ne '\r')"
        screen -x minecraft -p 0 -X stuff "save-on$(echo -ne '\r')"
    fi
}

server_status() {
if ["$(screen -ls | grep aim)" == ""] ; then
    echo -e "Aim --- ${txtred}${txtbld}Offline${txtrst}"
else
    echo -e "Aim --- ${txtgrn}${txtbld}Online${txtrst}"
fi
sleep 1
if ["$(screen -ls | grep badwater)" == ""] ; then
    echo -e "Badwater --- ${txtred}${txtbld}Offline${txtrst}"
else
    echo -e "Badwater --- ${txtgrn}${txtbld}Online${txtrst}"
fi
sleep 1
if ["$(screen -ls | grep deathrun)" == ""] ; then
    echo -e "Deathrun --- ${txtred}${txtbld}Offline${txtrst}"
else
    echo -e "Deathrun --- ${txtgrn}${txtbld}Online${txtrst}"
fi
sleep 1
if ["$(screen -ls | grep event)" == ""] ; then
    echo -e "Event --- ${txtred}${txtbld}Offline${txtrst}"
else
    echo -e "Event --- ${txtgrn}${txtbld}Online${txtrst}"
fi
sleep 1
if ["$(screen -ls | grep jailbreak)" == ""] ; then
    echo -e "Jailbreak --- ${txtred}${txtbld}Offline${txtrst}"
else
    echo -e "Jailbreak --- ${txtgrn}${txtbld}Online${txtrst}"
fi
sleep 1
if ["$(screen -ls | grep left4dead2)" == ""] ; then
    echo -e "Left4Dead2 --- ${txtred}${txtbld}Offline${txtrst}"
else
    echo -e "Left4Dead2 --- ${txtgrn}${txtbld}Online${txtrst}"
fi
sleep 1
if ["$(screen -ls | grep minecraft)" == ""] ; then
    echo -e "Minecraft --- ${txtred}${txtbld}Offline${txtrst}"
else
    echo -e "Minecraft --- ${txtgrn}${txtbld}Online${txtrst}"
fi
sleep 1
if ["$(screen -ls | grep skillsurf)" == ""] ; then
    echo -e "SkillSurf --- ${txtred}${txtbld}Offline${txtrst}"
else
    echo -e "SkillSurf --- ${txtgrn}${txtbld}Online${txtrst}"
fi
}

case $CMD in
	stop)
		server_stop
	;;
	start)
		server_start
	;;
	update)
		server_update
    ;;
	status)
		server_status
	;;
    restart)
        server_restart
    ;;
    backup)
        server_minecraft_backup
    ;;
	*)
		server_usage 
esac

exit 0

```

I am wanting it to Update / Start / Restart loads of servers using only 1 command.

For example

./tmf.sh start-all  
./tmf.sh stop-all  
./tmf.sh update-all

---

<div class="post-metadata">

**Author:** ![Corona688](https://community.unix.com/letter_avatar/corona688/32/6_449c533f586939b6e5f246632a46421f.png) [@Corona688](https://community.unix.com/u/Corona688)\
**Post date:** [October 14, 2011, 4:16pm UTC](https://community.unix.com/t/using-the-foreach-loop-needing-help/297249/4 "2011-10-14T16:16:08Z")

</div>

If you don't mind hardcoding the names:

```nohighlight
	start-all)
                for CMD in a b c d
                do
                        server_start
                done
	;;

```

If you want the script to handle all services in a folder, like daemons/service1/ and daemons/service2/ ...

```nohighlight
	start-all)
                cd daemons
                for CMD in *
                do
                        server_start
                done
                cd
	;;

```

If that's not enough to get you started I'll need to see how your files are organized too. This just keeps raising more and more questions 😛

---

<div class="post-metadata">

**Author:** ![grahamn95](https://community.unix.com/user_avatar/community.unix.com/grahamn95/32/7428_2.png) [@grahamn95](https://community.unix.com/u/grahamn95)\
**Post date:** [October 14, 2011, 4:20pm UTC](https://community.unix.com/t/using-the-foreach-loop-needing-help/297249/5 "2011-10-14T16:20:32Z")

</div>

Right what happens is when you type

```nohighlight
./tmf.sh start event

```

\<\< Example

```nohighlight
./tmf.sh $CMD $SRV

```

\<\< Structure

so when you do that example it would do this

cd event/css \<\<Goes to that servers directory  
./event.sh \<\< Starts the server using another small script which has the custom IP and that in there for starting it  
cd \<\< Goes back to the home directory

---

<div class="post-metadata">

**Author:** ![Corona688](https://community.unix.com/letter_avatar/corona688/32/6_449c533f586939b6e5f246632a46421f.png) [@Corona688](https://community.unix.com/u/Corona688)\
**Post date:** [October 14, 2011, 4:34pm UTC](https://community.unix.com/t/using-the-foreach-loop-needing-help/297249/6 "2011-10-14T16:34:17Z")

</div>

Okay, so you have a folder with one folder per service.

```nohighlight
# Starts all daemons. Overrides the CMD variable.
# Works by checking all folders in the current dir.
for SRV in * 
do
        [-d "$DIR"] || continue # Skip non-directories
        server_start
done

```
