0

I've got a sync script that runs a few rsync and rclone commands. I'd like to add an easy way to run the script in dry mode by default by passing the '-n' switch. I'm running into an issue with this because no matter what I try the commands see '' at the end of the command and fail.

The goal is to be able to run the script without any arguments and have it default to including the '-n' at the end of the command without having to duplicate the commands in the script to include one set with '-n' and one set without. Then running it with an argument at the end to run the actual sync.

A quick example is this using ls:

#!/usr/bin/env bash
set -x

FOLDER="/tmp/test"

ls -lha "$([ -z $1 ] || echo $FOLDER)"

./test.sh test                                                                                                                   Tue Feb 15 16:06:19 2022
+ FOLDER=/tmp/test
++ '[' -z test ']'
++ echo /tmp/test
+ ls -lha /tmp/test
./test.sh                                                                                                                            Tue Feb 15 16:05:07 2022
+ FOLDER=/tmp/test
++ '[' -z ']'
+ ls -lha ''
ls: cannot access '': No such file or directory

The goal is to get ls -lha '' to be ls -lha. Any help is greatly appreciated!

Tom L.
  • 3

1 Answers1

2
#!/bin/sh

dir=/tmp/test

ls -lha ${1+"$dir"}

The variable expansion ${variable+value} expands to value if the variable is set. It expands to nothing if the variable is not set. Use ${variable:+value} (i.e. ${1:+"$dir"} in the script above) if you want the expansion to expand to value only when the variable is set to a non-empty value.

Kusalananda
  • 333,661