Bash commands run at terminal but not in Jenkins/Bash Script

It looks like you want to ssh into my.host.example.com, then have the rest of the script run on that host. If this is the case, you need to pass the rest of the script as input to the ssh command; as it is now, ssh is taking input from the script's stdin which is probably empty, so it opens a remote shell session, sends it an end of file, which closes the ssh session and executes the rest of the script locally. In order to run those commands remotely, you need to pass them as input to the ssh command, something like this:

ssh -i ~/.ssh/id_rsa [email protected] <<EOF

echo "Extracting generated HTML into www directory..."
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
[...]
exit
EOF

Secondly, the script has no error checking. In general, it's a good idea to look at each command in a script, and ask yourself what would happen if it failed. Should the rest of the script continue, or would it "run off the rails" and do something silly? For example, if the scp command were to fail (for whatever reason), there wouldn't be any point in running the rest of the script (and it might be destructive, wiping out /var/www/html/subdir and then replacing it with... oops, nothing). You can either run an error check on each individual command's exit status, something like:

scp -i ~/.ssh/id_rsa html.zip [email protected]:/home/user || {
    echo "Failed to scp the html files to my.host.example.com." >&2
    exit 1
}

... or use the shell's -e option to make it exit the script if any command fails. This option saves you from having to error-check each command individually, but doesn't give informative error messages, and can cause trouble by exiting the script if something that doesn't matter returns an error status for some reason (see BashFAQ #105 for some examples of why -e can cause unexpected behavior). Also, if you do go with this option, make sure you use set -e both at the beginning of the script (or use -xe on the shebang line), and add set -e as the first command sent to the remote computer.

BTW, the cd command at line 4 is particularly likely to fail, since it uses a relative path. This means that the directory it tries to cd to depends on the working directory the script was started from. Note that this is not necessarily the directory the script is in, it's inherited from the process that started the script and hence could be almost anything. Jenkins may be starting the script with a different working directory than you are, thus causing it to fail right out of the gate. Well, not actually fail, just run all the remaining commands in the wrong directory (and because of the ssh input problem, on the wrong host).


When you copy, delete or move files, modify your script to use an absolute path. Currently you have these lines

rm ./html.zip cp -r ./subdir/* /var/www/html/subdir/

change the ./ part to the full path to that file or directory.