1

I have a single file shell script (BusyBox, no bash, ksh I believe) that I want to write a path to itself when run. I need #home to be replaced by home=/home. I have this:

var="/home"
#home
sed -i 's/#home/home=$var/g' /this/file.sh

When run it'll replace #home and the string in the sed line and the $var is not expanded:

var="/home"
home=$var
sed -i 's/home=$var/home=$var/g' /this/file.sh

This is my desired outcome:

var="/home"
home=/home
sed -i 's/#home/home=$var/g' /this/file.sh

I'm pulling my hair getting this to work. Any hints?

Answering myself this works as expected:

var="/home"
#home
sed -i "s|^#home|home=${var}/|g" m.sh
stargazer
  • 91
  • 1
  • 9

1 Answers1

2

While there may be several ways to address this question. Try adding the circumflex (^) at the beginning of the pattern to indicate that this pattern should be found at the beginning of the line.

Before running the script (here it is named m.sh)

#!/bin/bash

var="/home"
#home
sed -i 's/^#home/home=$var/g' m.sh

After running the script

#!/bin/bash

var="/home"
home=$var
sed -i 's/^#home/home=$var/g' m.sh

EDIT You may also want to consider removing the g modifier in sed since you only want to match once in the line.

Harald
  • 3,110
  • 1
  • 24
  • 35