This Bash script is a wrapper for the rsync command, and its main purpose is to process the command-line arguments passed to it by removing trailing slashes from directory paths — except when the path is just /.
Let's walk through what each part does:
Full Explanation
bash
#!/bin/bash
This line specifies that the script should be run using the Bash shell.
bash
new_args=()
Initializes an empty array called new_args which will store the modified command-line arguments.
bash
for i in "${@}"; do
Iterates over all the arguments ("${@}") passed to the script. Each argument is stored temporarily in the variable i.
The quotes around ${@} ensure that arguments containing spaces are handled correctly.
bash
case "${i}" in
/)
i="/"
;;
If the argument is exactly /, leave it unchanged.
This special case avoids accidentally modifying the root directory path.
bash
*/)
i="${i%/}"
;;
If the argument ends with a /, remove the trailing slash.
${i%/} removes the shortest match of / from the end of the string (i.e., the trailing slash).
Example:
Input: /home/user/
Output: /home/user
bash
esac
Ends the case statement.
bash
new_args+=("${i}")
Adds the potentially modified argument ($i) to the new_args array.
bash
done
Ends the for loop.
bash
exec rsync "${new_args[@]}"
Replaces the current shell process with the rsync command, passing the modified arguments.
"${new_args[@]}" expands to all elements of the array as separate arguments, preserving spaces and special characters.
Why Is This Useful?
The reason for removing trailing slashes from paths in rsync is subtle but important:
In rsync, if you include a trailing slash on a source directory (e.g., /source/), it means copy the contents of the directory, not the directory itself.
If you pass /source (no slash), it copies the directory and its contents.
By normalizing paths to remove trailing slashes, this script ensures consistent behavior — especially useful when arguments come from user input or other scripts where trailing slashes might appear inconsistently.
However, note that this normalization could change the behavior of rsync depending on whether the trailing slash was intentional.
Example Usage
Suppose you run:
bash
./myrsync.sh -av /home/user/docs/ /backup/
The script processes the paths:
/home/user/docs/ → /home/user/docs
/backup/ → /backup
Then it runs:
bash
exec rsync -av /home/user/docs /backup
Summary
This script wraps the rsync command and ensures that:
Trailing slashes are removed from all paths except the root /.
This makes the behavior of rsync more predictable when paths come with optional trailing slashes.
It’s particularly useful in automation or wrappers where you want to normalize how paths are passed to rsync.