1

I'm trying to update a variable:

FLUX=first
DATE=`date +%Y%m%d_%H_%M`
justName=$FLUX
DIR_LOG=$REP_LOG_TD/DDL_TABLES_LOG/$justName'_'$DATE
if [ condition ]
then
 justName=other
 DIR_LOG=$DIR_LOG
fi   

The variable is DIR_LOG and I want to update justName when condition is true.

The result that I want is

/root/log/DDL_TABLES_LOG/other_20181205_09_49

but I get

/root/log/DDL_TABLES_LOG/first_20181205_09_49

How to change the justName component?

JigglyNaga
  • 7,886
SGUser
  • 15
  • 4

1 Answers1

2

If you break this down using sh -x, you'll see the problem:

+ FLUX=first
++ date +%Y%m%d_%H_%M
+ DATE=20181205_12_25
+ justName=first
+ DIR_LOG=/test/DDL_TABLES_LOG/first_20181205_12_25
+ '[' true ']'
+ justName=other
+ DIR_LOG=/test/DDL_TABLES_LOG/first_20181205_12_25

Note that the DIR_LOG variable is set before the condition is evaluated. Even when the condition evaluates to true, you'll get the same value for the DIR_LOG variable.

To change the behaviour, change the order of assignment as shown below:

FLUX=first
DATE=$(date +%Y%m%d_%H_%M)
justName=$FLUX
if [ true ]
then
justName=other
fi
DIR_LOG=/test/DDL_TABLES_LOG/$justName'_'$DATE

Again, with sh -x:

+ FLUX=first
++ date +%Y%m%d_%H_%M
+ DATE=20181205_12_28
+ justName=first
+ '[' true ']'
+ justName=other
+ DIR_LOG=/test/DDL_TABLES_LOG/other_20181205_12_28

With this approach, you're setting the value of the justName variable first, before evaluating the DIR_LOG variable. This will get you the required output.

Note: The condition has been assumed to be true for convenience. When the condition fails, you'll see the output as shown below:

+ FLUX=first
++ date +%Y%m%d_%H_%M
+ DATE=20181205_12_32
+ justName=first
+ false
+ DIR_LOG=/test/DDL_TABLES_LOG/first_20181205_12_32
Haxiel
  • 8,361