1

Script A imports all variables from B script; the problem is script B, I do not know if exist or is empty the variable as I need. Case not exist variable in B, then I use my variable in script A. case it exist in A use my variable B; or it exist in A and B then use for default variable in B.

Example: In this case the variable Comment3 in my script "B" is empty...

script B.sh

#!/bin/sh
Name='<b>Variety</b>'
Comment='<span size="xx-large">Variety changes the wallpaper on a regular interval</span>'
Comment3=''
License='GPLv3'
Screenshot='http://peterlevi.com/variety/wp-content/uploads/2012/10/01-all-1024x576.jpg'
Url='http://peterlevi.com/variety/'
export Comment
export Name
export Comment3
export License
export Screenshot
export Url

Script A.sh

#!/bin/sh
. $HOME/B.sh
Comment2='Variety changes the desktop wallpaper on a regular basis, using user-specified or automatically downloaded images.'

echo $display_variable_comment3_or_comment2 (depending the case)

sorry my english is bad :/

davidva
  • 25
  • 6

2 Answers2

4

In BASH you can do this:

pvar="${s:-defaultVal}"

Then pvar will be set to $s if it exists otherwise it will be set to defaultVal

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Excellent! thanks! work great! I only renamed the variable 'Comment3' to 'Comment2' in my script "A.sh"; and also made a new variable called pvar in my script 'A.sh': pvar="${Comment2:-$Comment3}" – davidva Mar 13 '14 at 06:23
1

It depends on whether you need to check if the variable exists or if it's value is empty. If you need only to test if it is empty you can use this:

if [ -z "$COMMENT3" ] ; then
    COMMENT3="some comment"
fi

... otherwise use @anubhava's answer.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 1
    `[ -z $COMMENT3 ]` is a bad idea, because the OP's example suggests that `$COMMENT3` is likely to contain whitespace and so on. How about `[ -z "$COMMENT3" ]` instead? – ruakh Mar 13 '14 at 01:59
  • @ruakh You are right, I missed that – hek2mgl Mar 13 '14 at 09:05