1

When I do that:

VAR1="My_ID"
VAR2="/Path/to/some/resource/$VAR1/in/local/machine"
echo $VAR2 

then output is:

/Path/to/some/resource/Special/My_ID/local/machine

But when

ID="Some_ID"
CONFIG_FILE="/etc/config.file"
VAR3=`grep -i "^shell=" $CONFIG_FILE` #output is: shell=/usr/bin/program -t path/to/some/data/$ID/state -o output
VAR3=${VAR3#*"-t"} #output is: path/to/some/data/$ID -o output
VAR3=`echo $VAR3 | cut -d ' ' -f 1`  #output is: path/to/some/data/$ID/state
echo $VAR3
echo $ID

then output is:

path/to/some/data/$ID/state
Some_ID

How to achieve that VAR3 will give output

path/to/some/data/Some_ID/state

Try search in google similar cases but no found

2
  • Another way is to use sed instead of grep;${VAR3#...};cut -d: Try this: VAR3="$(sed "/^shell=/{ s/.* -t *\([^ ]\+\) .*/\1/;s/\$ID/$ID/;q;};d" $CONFIG_FILE)" Commented Oct 31, 2024 at 11:26
  • Great @Krzysiek . If it fixed your problem, please mark it as the correct answer. Commented Dec 4, 2024 at 8:43

2 Answers 2

1

A solution would be to replace the literal $ID string in the Path with the actual value of $ID as such

VAR3="${VAR3/\$ID/"$ID"}"

In your code:

ID="Some_ID"
CONFIG_FILE="/etc/config.file"
VAR3=`grep -i "^shell=" $CONFIG_FILE` #output is: shell=/usr/bin/program -t path/to/some/data/$ID/state -o output
VAR3=${VAR3#*"-t"} #output is: path/to/some/data/$ID -o output
VAR3=`echo $VAR3 | cut -d ' ' -f 1`  #output is: path/to/some/data/$ID/state
VAR3="${VAR3/\$ID/"$ID"}"
echo $VAR3
echo $ID

See following source for additional information: https://linuxhandbook.com/replace-string-bash/

Sign up to request clarification or add additional context in comments.

2 Comments

Juste one line VAR3= instead of 4: VAR3="$(sed "/^shell=/{ s/.* -t *\([^ ]\+\) .*/\1/;s/\$ID/$ID/;q;};d" $CONFIG_FILE)"
Thank you, adding VAR3="${VAR3/\$ID/"$ID"}" resolve my problem
0

The code presented in the question contains some bad practices. Remember to check your scripts with shellcheck .

In the first presented code example, the $VAR1 string is replaced when Bash executes the assignment VAR2="..." line. The right side of = is inside " quotes, so $VAR1 is expanded, as are the rules in shell.

To run variable expansion inside a string, typically use envsubst:

VAR1="My_ID"
VAR2='/Path/to/some/resource/$VAR1/in/local/machine'
VAR1="$VAR1" envsubst <<<"$VAR2"

See man envsubst, or for example Bash Templating: How to build configuration files from templates with Bash? .

2 Comments

The question is tagged bash and not linux, and envsubst is not a bash feature nor is available everywhere bash is, not even on all Unix systems.
Using sed may be shorter: VAR3="$(sed "/^shell=/{ s/.* -t *\([^ ]\+\) .*/\1/;s/\$ID/$ID/;q;};d" $CONFIG_FILE)"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.