Sunday, March 8, 2015

Shell script argument with a default value

So, I made I shell script which makes some backup copies. I want it to accept one argument which is the directory where to store the backups. And if it was not provided, it should have some default value.

This works:
#!/bin/sh
if [ -z "$1" ]; then
    BACKUP_DIR="/home/ubuntu/backups"
else
    BACKUP_DIR="$1"
fi
echo "${BACKUP_DIR}"

But it's too verbose. Of course you could write it in one line, but here is a nicer version:
[ -z "$1" ] && BACKUP_DIR="/home/ubuntu/backups" || BACKUP_DIR="$1"

But the variable name is repeated twice. We can do better:

BACKUP_DIR=$([ -z "$1" ] && echo "/home/ubuntu/backups" || echo "$1")

But I think this is the clear winner:

BACKUP_DIR=${1:-"/home/ubuntu/backups"}

${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

No comments:

Post a Comment