4

I have a command that spits as an output another command. I'd like to run this output in a makefile script.

The simpler command I could reproduce is

awsecrpush:
    VAR=$$( sudo echo "ls -lah" ) | bash -c "sudo -s $$VAR"

What are my results:

  • Running make
    $ make
    VAR=$( sudo echo "ls -lah" ) | bash -c "sudo -s $VAR"
    echo $VAR
    {empty output}
  • But running ls -lah, it works as expected. That's what I want from my makefile
$ ls -lah
total 405
-rw-rw-r--  1 garry garry  405 jul 22 10:59 Makefile

That's only to simplify my question because I have a complex command to execute.

I need this approach just because I need append SUDO in front of ls -lah

1 Answer 1

3

The problem is that, by using |, you're running the two commands (the assignment of VAR and the sudo command using it) in separate subshells, so you're setting the variable in a shell while trying to use it in another one.

Furthermore, there's really no need for a pipe, since you're not really passing any output from the first command to the standard input of the second (ls doesn't really take anything on stdin.)

Just replacing | with a ; should make this work for you. (Using && would also be good, since then it only runs the sudo part if the command generating the contents of the variable succeeds.)

Note that you need both in the same line, since make normally spawns a shell for each separate line in the recipe. You need both running on the same shell, otherwise you will set VAR from one shell and try to consume it from a separate shell, which will again not work.

awsecrpush:
        VAR=$$( sudo echo "ls -lah" ) && bash -c "sudo -s $$VAR"

Another possibility is to use a Make variable instead. That's somewhat more flexible in that you might not need to worry so much about subshells.

Assuming you have GNU make, you can use the shell function to run the first command and save its output in a Make variable.

awsecrpush:
        VAR := $(shell sudo echo "ls -lah")
        sudo -s $(VAR)
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .