Deleted
Deleted

Reputation: 4227

Exactly what does env do in Bash?

I get this behavior when using Bash (under Cygwin):

$ printf '\u00d5'
\u00d5
$ env printf '\u00d5' # This results in the behavior I want
Õ

It does not matter if I use UTF-8 or ISO-8859-1 encoding in the terminal.

My questions are: Exactly what does env do? Why do I need it in this specific case?

Upvotes: 13

Views: 5340

Answers (1)

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143279

env is not in bash, it's a standalone executable, it is used to set or clear environment variable before running program. In your particular case, it's running the binary printf instead of the shell builtin. You can achieve the same result by using the absolute path:

/usr/bin/printf '\u00d5'

The least intrusive method is perhaps the following: redefine the printf function and have Bash handle the rest. Source a file that contains the following:

function printf()
{
  $(which printf) "$@"
}

or as a one-liner function printf() { $(which printf) "$@"; }. Of course you could replace the $(which printf) for a /usr/bin/printf ...

Then simply use printf as you're used to. Your script stays the same and you could even introduce a condition to define the function only on certain Bash versions.

AFAIK you can also leave out the function, but I find it adds to readability.

[EDIT: the function keyword is a bash extension; printf () { ...; } is the POSIX syntax. If you do use the function keyword, the () after the function name are optional.]


Commonly, env is also used in the hash-bang lines of scripts that strive to be portable. The reason being that env is nearly always at /usr/bin/env, while bash isn't always at /bin/bash as many a hash-bang line implies. Example:

#!/usr/bin/env bash

also works for other programs/interpreters:

#!/usr/bin/env python

Upvotes: 17

Related Questions