Friday, November 13, 2009

Bash: Default Variable Values from Command Line Arguments

I wanted to have a bash script that takes one command line argument, but would default to a given value if the argument was ommitted. Here's a simple test script that demonstrates how I can do it:
  #!/bin/bash
VAR=default
if [ -n "$1" ]; then
VAR=$1
fi
echo $VAR
The -n operator tests that a string is not null and is quoted which is considered a good practice.

If I run the script, with no arguments, default is output to the screen, otherwise the argument is displayed.
  prystasj:~$ ./test.sh
default
prystasj:~$ ./test.sh hello
hello

2 comments:

  1. This can be achieved by echo ${1:-default} or VAR="${1:-default}"

    ReplyDelete
  2. From POSIX: ${parameter:-word}

    Use Default Values. If parameter is unset or null, the expansion of word shall be substituted; otherwise, the value of parameter shall be substituted.

    ReplyDelete