C.W.K.
Stream
Lesson 05 of 14 · published

Remote Execution & Quoting

~12 min · remote-exec, quoting, heredoc

Level 0Pinger
0 XP0/101 lessons0/12 achievements
0/150 XP to next level150 XP to go0% complete

One-shot commands

You don't always need an interactive SSH session. ssh host 'command' runs the command on the remote and exits. Combine that with the parallel patterns and you have a fleet command shell.

The quoting trap

Quoting in SSH is where most surprises happen. The rule: single quotes mean "evaluate on the REMOTE side." Double quotes mean "local shell expands first, then send the result remote." When in doubt, single quotes. When you need a local variable embedded into a remote command, use the heredoc pattern.

Code

Single vs double quotes·bash
# Single quotes — evaluated on the remote machine
ssh office 'echo $HOME'
# Output: /Users/you_username (remote user's home)

# Double quotes — evaluated locally first!
ssh office "echo $HOME"
# Output: /Users/you_username (your LOCAL home — possibly the wrong answer)

# Want both? Escape the dollar to delay expansion to remote
ssh office "echo \$HOME"

# When in doubt, echo the command first to see what gets sent
echo "echo $HOME"
echo 'echo $HOME'
Multi-line via heredoc·bash
# Quoted heredoc — entire block runs on the remote unchanged
ssh office <<'EOF'
echo "Hostname: $(hostname)"
echo "Uptime: $(uptime)"
echo "Disk: $(df -h / | tail -1)"
EOF

# Unquoted heredoc — local variables expand first
NOW=$(date)
ssh office <<EOF
echo "From local: ${NOW}"
echo "From remote: $(hostname)"
EOF
# Note: $(hostname) here runs LOCALLY — usually not what you want
# Use the quoted form 99% of the time

External links

Exercise

On any machine, run both ssh office 'echo $HOME' and ssh office "echo $HOME". Note the difference. Then construct a heredoc that runs three commands on the remote (hostname, df, uptime) — use the <<'EOF' form. This is the fleet automation primitive you'll use constantly.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.