Is it possible to write an identity function in Bash (relative to the arguments passed / returned)

Such an “identity” function must satisfy the following two properties:

identity $(identity a\ b c\ d)
# (Expected output:)
# a b
# c d

And, given the following function "argv_count":

argv_count () { echo "argv_count('$@'):$#"; }
argv_count $(identity a\ b c\ d)
# (Expected output:)
# argv_count('a b c d'):2

If necessary, additional quotation marks in the tests may be required.

A simple candidate, such as the following, cannot pass the second test:

identity () { for arg in "$@"; do echo "$arg"; done; }

cat is not the right solution as it is an identity function regarding stdin | stdout

+3
source share
2 answers

, . , ( $(somecommand)), , . , identity , (.. ) , //, . , ( ). , $(identity 'foo * bar') .

, . , set -f , , , identity, . , IFS, , , , , , , fakery.

EDIT: , eval - "" , .

+6

eval, :

$ argv_count a\ b c\ d
argv_count('a b c d'):2
$ identity() { printf ' %q' "$@"; }
$ eval argv_count "$(identity a\ b c\ d)"
argv_count('a b c d'):2
$ eval argv_count "$(eval identity "$(identity a\ b c\ d)")"
argv_count('a b c d'):2

:

$ argv_count $'foo\t * bar'
argv_count('foo  * bar'):1
$ eval argv_count "$(eval identity "$(identity $'foo\t * bar')")"
argv_count('foo  * bar'):1
+2

All Articles