Home > Software design >  bash command with escaped TAB ('\t') character fails in Makefile
bash command with escaped TAB ('\t') character fails in Makefile

Time:11-16

In a Makefile (gnu make, on an Ubuntu system), I have the following commands:

.PHONY: stack-use
stack-use: $(BUILD_PATH)/$(TARGET).elf
    @cat build/*.su | sort -t$$'\t' -k2 -nr | awk -F'\t' '{ if($$2>0) {print $$0}}' | column -s$$'\t' -t

When running make -n stack-use, I get

$ make -n stack-use 
cat build/*.su | sort -t$'\t' -k2 -nr | awk -F'\t' '{ if($2>0) {print $0}}' | column -s$'\t' -t

and running the printed command produces the output I want.

However, the problem is that when I run it from within make, I get:

sort: multi-character tab ‘$\\t’

So it seems that the backslash character gets escaped, and the shell command therefore does not 'see' the intended TAB ('\t') character but a backslash followed by a 't'.

How can I fix this?

UPDATE: based on the suggestion below, the final working code is

    @cat build/*.su | sort -t"$(printf '\t')" -k2 -nr | awk -F'\t' '{ if($2>0) {print $0}}' | column -s"$(printf '\t')" -t

CodePudding user response:

As the comments note, you are not using bash here.

You can either force your makefile to use bash as its shell by adding this:

SHELL := /bin/bash

Or you can rewrite your command to use POSIX-conforming syntax. For example maybe replace -t$$'\t' with "-t$$(printf '\t')".

  • Related