1

Value of a Variable in Shell Script based on the condition mentioned in the IF statement.

I have a shell script, I want to assign a variable based on the condition in if statement.

For Eg:

    build(){
    
     SRC_TBL=$1

     filename=`echo $SRC_TBL | sed 's/_//g'`

     target_tbl=`echo $SRC_TBL | tr '[a-z]' '[A-Z]'`

     if [["${target_tbl}" == "DEMO" ]];then
        target_tbl= "TEST"
     fi
    
    }

build "DEMO"

I am running the above function, so according to the logic the value of the variable target_tbl should be TEST, but it is still DEMO.

Help me where am I going wrong

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 3
    check your script with shellcheck – KamilCuk Feb 21 '23 at 11:53
  • 2
    Can you put the exact script you are using? This one does not work, and your issue probably is in one of those details you didn't care here. – Poshi Feb 21 '23 at 12:15
  • 1
    "Does not work" in the sense that it tries to execute `[[DEMO` as a command. And if that were fixed then there is at least one other error that would interfere with the result you seem to expect. You should be getting some kind of diagnostic indicating the nature of the issue, unless you are suppressing it. This sort of thing is among the reasons that we request that people posing debugging questions provide a [mre] that demonstrates the issue. Not only does that help us help you, but often it even helps you to help yourself. – John Bollinger Feb 21 '23 at 12:48

1 Answers1

1

There are several issues with your script.

  1. assignment must NOT have spaces around =
  2. there MUST be a space after [[

Here's the script fixed and working fine:

#!/usr/bin/env bash


build() {

  SRC_TBL=$1

  filename=$(echo "$SRC_TBL" | sed 's/_//g')

  target_tbl=$(echo "$SRC_TBL" | tr '[a-z]' '[A-Z]')

  if [[ "$target_tbl" == "DEMO" ]]; then
    target_tbl="TEST"
  fi
  printf "%s" "$target_tbl"
}

build "DEMO"

enter image description here

some resources for the future:

https://github.com/dylanaraps/pure-bash-bible

https://www.shellcheck.net/

Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51