0
votes

I make deploy Bash script and I have a problem. I don't understand how I can use if/else for select server and run commands on server. I'd like run script with params:

sh deploy.sh beta

or

sh deploy.sh production

My script:

#!/bin/bash

production='user@production_server'
beta='user@beta_server'
demon_path='demon'
params=$1

if [[ params == "production" ]]
  then ssh -A $production
else
  ssh -A $beta
fi

"
cd $demon_path

git checkout master
git pull --rebase

touch restart.txt

exit
"
3
It's a Bash script. Don't execute it with sh.gniourf_gniourf

3 Answers

3
votes

Very simply,

#!/bin/bash

if [[ "$1" == "production" ]]; then
    server='user@production_server'
else
    server='user@beta_server'
fi

ssh -A "$server" "cd demon
    git checkout master
    git pull --rebase
    touch restart.txt"
0
votes

The here document can help you

you can use custom delimiters for a set of commands to be excecuted on the server as

ssh user@hostname << EOF
#some commands to be excecuted.
EOF

The if construct in you program can be modified as

if [[ "$params" == "production" ]]
  then 
    ssh -A $production << EOF
       cd $demon_path

       git checkout master
       git pull --rebase

       touch restart.txt
    EOF
else
    ssh -A $beta << EOF
       cd $demon_path

       git checkout master
       git pull --rebase

       touch restart.txt
    EOF
fi

this enables the commands before EOF to be excecuted in the production_server

0
votes

You could use some bash-specific features, like associative arrays:

#!/bin/bash

declare -A dest=(
    [production]='user@production_server'
    [beta]='user@beta_server'
)
demon_path='demon'

if [[ -z ${dest[$1]} ]]; then
    echo "error: choose one of ${!dest[*]}"
    exit 1
fi

ssh -a "${dest[$1]}" <<END
cd $demon_path && {
    # only execute the git commands if cd succeeded
    git checkout master
    git pull --rebase
    touch restart.txt
}
END