Skip to content

Instantly share code, notes, and snippets.

@tedpearson
Last active December 20, 2024 22:43
Show Gist options
  • Save tedpearson/29fa9f37d57ba1926840054556e90331 to your computer and use it in GitHub Desktop.
Save tedpearson/29fa9f37d57ba1926840054556e90331 to your computer and use it in GitHub Desktop.
Replace a file via ssh on a server
#!/usr/bin/env bash
# Replce a file on a server
# replace-remote-file.sh
if [[ $# -lt 5 || $# -gt 6 ]]; then
echo "Usage: replace-remote-file /path/to/local/file /path/to/remote/file chown restart-cmd hostname [bak-suffix]"
exit 1
fi
local_file="$1"
remote_file="$2"
chown="$3"
restart_cmd="$4"
hostname="$5"
bak="$6"
if [[ -z "$bak" ]]; then
bak=".bak"
fi
copied_filename=$(basename "$remote_file")
scp "$local_file" "${hostname}:${copied_filename}"
ssh -t "${hostname}" sudo chown "${chown}" "${copied_filename}"
ssh -t "${hostname}" sudo cp "${remote_file}" "${remote_file}${bak}"
ssh -t "${hostname}" sudo mv "${copied_filename}" "${remote_file}"
ssh -t "${hostname}" sudo "${restart_cmd}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment