6

Why does this work:

$ cat test.sh
#!/bin/bash
cat <(date|awk '{print $1}')

$ ./test.sh
Thu

but not as a command passed to bash:

$ bash -c "cat <(date|awk '{print $1}')"
Thu  2 Apr 2020 12:52:10 BST

I'm running this on macOS

$ bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin19)
Copyright (C) 2007 Free Software Foundation, Inc.

1 Answer 1

22

In your one-liner, the $1 is within a double quoted string:

"cat <(date|awk '{print $1}')"

This means that it will be expanded by the interactive shell. If the first positional parameter, $1, is empty, it will expand it to an empty string, resulting in an awk program that just prints its input:

awk '{print }'

Escape the $ in $1 as \$1 to stop the shell from trying to expand it. Your complete command would then look like

bash -c "cat <(date|awk '{print \$1}')"

In your script variant, the $1 is in a single quoted string. The shell will therefore not try to expand it.

In this specific case though, it would be better to use just

date +%a

to print the abbreviated name of the day. See also the strftime(3) manual (man 3 strftime).

In newer bash versions (release 4.2+, i.e. not with the default bash on macOS, but with the one installed through e.g. Homebrew),

printf '%(%a)T\n' -1

would do the same thing without invoking any external commands.

You must log in to answer this question.

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