Bryan Hanson
Bryan Hanson

Reputation: 6213

Calling a shell function (in an external file) with arguments from a makefile

I have a file sedstr.sh containing a function sedstr:

#!/bin/bash
function sedstr {
# From stackoverflow.com/a/29626460/633251 (Thanks Ed!)
    old="$1"
    new="$2"
    file="${3:--}"
    escOld=$(sed 's/[^^]/[&]/g; s/\^/\\^/g' <<< "$old")
    escNew=$(sed 's/[&/\]/\\&/g' <<< "$new")
    sed -i.tmp "s/\<$escOld\>/$escNew/g" "$file" # added -i.tmp
    echo "sedstr done"
}

I have an external file "test" to be edited in place with these contents:

My last name is Han.son and I need help.
If the makefile works, I'll have a new last name.

I want to call the sedstr function with its arguments from a makefile. Nothing should be returned, but the external file should be edited. Here is a small makefile that doesn't work:

all: doEdit

doEdit:
  $(shell ./sedstr.sh) # I was hoping this would bring the function into the scope, but nay
  $(shell sedstr 'Han.son', 'Dufus', test)

How can I call this function using variables in the makefile? The error is:

make: sedstr: Command not found
make: Nothing to be done for `all'.

Upvotes: 1

Views: 1418

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80921

Each line in a make recipe is executed in its own shell.

Similarly, so is each call to $(shell).

They don't share state.

To do what you want ould would need a recipe line of

$(shell . ./sedstr.sh; sedstr 'Han.son' 'Dufus' test)

That being said there's no reason to use $(shell) here at all as you are already in a shell context and as you can just as easily (and more correctly) use a recipe line of

. ./sedstr.sh; sedstr 'Hans.son' 'Dufus' test

And yes, the commas in the original are just incorrect.

Upvotes: 4

Mikkel Christiansen
Mikkel Christiansen

Reputation: 137

You can call the function from inside sedstr.sh. At the end

sedstr "$1" "$2" "$3"

EDIT Or see other answer

Upvotes: 1

Related Questions