1

Possible Duplicate:
How to tell if a string is not defined in a bash shell script?
What’s the best way to check that environment variables are set in Unix shellscript

I'm trying my hand at Unix shell scripting for the first time and in a script I'm working on now, I want 2 of the 3 arguments to my script to be optional. However, if the user doesn't enter the arguments, I need to use default values. How can I properly say something that basically means:

$argument = $2
if($argument  == "")
    $argument = "defaultVal"

Thanks!

Community
  • 1
  • 1
JToland
  • 3,630
  • 12
  • 49
  • 70
  • `if [ "x$2" == "x" ]; then $argument="default"; fi` –  Oct 18 '12 at 19:57
  • I thought `$#` stored the number of input params? I could be wrong. – TheZ Oct 18 '12 at 19:57
  • `test -n` or `test -z` . Test is almost the same as `[`. – wildplasser Oct 18 '12 at 19:57
  • Possible duplicate of [What's the best way to check that environment variables are set in Unix shellscript](http://stackoverflow.com/questions/307503/whats-the-best-way-to-check-that-environment-variables-are-set-in-unix-shellscr), or you might prefer [How to tell if a string is not defined in a Bash shell script](http://stackoverflow.com/questions/228544/how-to-tell-if-a-string-is-not-defined-in-a-bash-shell-script/230593#230593) – Jonathan Leffler Oct 18 '12 at 20:17
  • It is vitally important to say *which* shell you are using. – dmckee --- ex-moderator kitten Oct 19 '12 at 04:12

2 Answers2

2

try:

argument=${2:-default value}
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • 1
    Both these answers seem to work great - I just accepted the first one I got working! Thanks to both of you for your quick replies! – JToland Oct 19 '12 at 14:45
1

Try this:

if [ "x$2" == "x" ]; then
    $argument="default";
else
    $argument=$2;
fi
  • Is that trick still necessary? `if [ "$2" = "" ];` works fine, in `bash` and `dash` at least. – chepner Oct 18 '12 at 22:39
  • @chepner I had problems with the "" being recognized as an empty token producing a syntax error, so I'd say yes. –  Oct 19 '12 at 04:44
  • 1
    Both these answers seem to work great - I just accepted the first one I got working! Thanks to both of you for your quick replies! – JToland Oct 19 '12 at 14:46