Search code examples
bashshellfor-loopvariables

Shell, Execute a command that needs to go through multiple values one by one


I have a script:

if [ $ModEnabled == "1" ];then
    ${HOME}/servers/steamcmd/steamcmd.sh +force_install_dir ${HOME}/servers/dayzserver/ +login "${SteamUser}"  +workshop_download_item 221100 1559212036 validate +quit
    printf "Done"
else
    echo "Variable is not set"
fi

However, what I need to do is to run that command +workshop_download_item 221100 1559212036 validate

Where it re-run/loops the command replacing the specific value "1559212036" with a list of multiple values.

The vision is: (fake code, obviously lol)

modlist={"
    123123123,
    234456567,
    456456456,
    567567567,"
}

then this runs:

${HOME}/servers/steamcmd/steamcmd.sh +force_install_dir ${HOME}/servers/dayzserver/ +login "${SteamUser}"  +workshop_download_item 221100 $modlist, then run again with the next item in modlist" validate +quit

If it is possible to do this without calling "+quit" everytime, thats a bonus (but I guess this is a steamcmd thing.


Solution

  • The construct you are looking for is a for loop.

    DayZModList="
        123123
        456456
        789789"
    
    if [ "${ModEnabled}" == 1 ] ; then
        for ModId in $DayZModList ; do
            "${HOME}"/servers/steamcmd/steamcmd.sh \
            +force_install_dir "${HOME}"/servers/dayzserver/ \
            +login "${SteamUser}" \
            +workshop_download_item 221100 "${ModId}" \
            validate +quit
        done
    
        echo "Done"
    else
        echo "Variable is not set"
    fi
    

    You set the iterator (I've used the variable name ModId, but you can use whatever you like) and then access it using (in this example) "${ModId}".