Creating remote directories in a bash script via ssh (with error trapping) I'd like to create directories on a remote VM, but only if they do not exist. What's more, if creating the directory results in an error (exit status != 0) I'd like the script to exit as well, or at least print an error. Is there a more succinct way to do this than what I have below? 

UPDATE: Just to clarify, I want to test -d first so mkdir -p won't produce output about the directory already existing.

#!/bin/bash

mydirs=(/var/www/files /var/www/photos /var/www/info)
for d in ${mydirs[@]}; do
   ssh remotehost "test -d $d"
   res=$?
   test $res -ne 0 &amp;&amp; { ssh remotehost "mkdir -p $d"; res=$?; }
   test $res -ne 0 &amp;&amp; { echo "error during mkdir on remote"; exit 1; }
done
Running ssh in a loop is not efficient. Since the script is not interactive,
you could pass the entire script to a remote Bash process on stdin,
so that loop will run entirely on the remote server, locally:

ssh remotehost bash &lt;&lt; "EOF"
mydirs=(/var/www/files /var/www/photos /var/www/info)
for d in ${mydirs[@]}; do
   test -d $d
   res=$?
   test $res -ne 0 &amp;&amp; { mkdir -p $d; res=$?; }
   test $res -ne 0 &amp;&amp; { echo "error during mkdir on remote"; exit 1; }
done
EOF


Notice the double-quotes around the here document label, this is to avoid variable interpolation. The entire script is passed to the remote shell literally.

I made only the minimal changes to illustrate the point. Some important improvements are well advised:


All variables used as command line arguments should be double-quoted: "${mydirs[@]}", "$d", and so on.
As a comment mentioned, when using mkdir -p, it's unnecessary to test if the directory exists.
Now that the main operations run in a single process, the pipeline can be simplified.
As another comment mentioned, consider investing in learning a proper system administration tool such as Puppet, Ansible, Chef, or similar.