Command Substitution in Bash VS Function Calling

Bash functions inside process substitution

There's no problem here:

$ chmod  +x test.sh 
$ ./test.sh

Clear diff. No problem!

$ bash -x ./test.sh 
+ diff /dev/fd/63 /dev/fd/62
++ testfunc
++ echo bork
++ echo bork

Proof that it worked

Troubleshooting:

Maybe you

  • run in a restricted shell
  • you don't have /dev/fd available/mounted correctly (due to somekind of secure chroot jail?)

What is the difference between $(command) and `command` in shell programming?

The backticks/gravemarks have been deprecated in favor of $() for command substitution because $() can easily nest within itself as in $(echo foo$(echo bar)). There are other differences such as how backslashes are parsed in the backtick/gravemark version, etc.

See BashFAQ/082 for several reasons to always prefer the $(...) syntax.

Also see the POSIX spec for detailed information on the various differences.

Bash: Pass Command Substitution to External Program (or Function) without Word Splitting

The key to correct quoting lies in the understanding what happens.

That echo "-htns crl" "qjkx" for example will print just a byte stream to its stdout, so it will be just -htns crl qjkx in the end. The information that -htns crl were grouped more closely than qjkx is lost.

To avoid this loss you can use printf "%q":

pyfg() {
printf "%q %q" "-htns crl" "qjkx"
}

This will generate quoted output: -htns\ crl qjkx which means to the shell the same as "-htns crl" "qjkx" (whether the space is escaped with a backslash or quoted with double quotes does not make a difference).

The next aspect is the use of $() to pass the output of one program to the next.

The typical way is to put that in double quotes:

aoeu "$(pyfg)"

This way everything is passed without interpretation which is desirable in most cases.

In your case, however, you might want to make the output of pyfg quoted instead of quote the output of pyfg; notice the important difference: The first means that pyfg produces quoted output (as shown above), the second means that pyfg produces output which gets quoted later. The second does not help if the output of pyfg already lost the information which parts belong together.

If you now just leave away the double quotes, the output unfortunately just gets split at the spaces (i. e. first character of $IFS) even if this space is escaped with a backslash. So, instead, you need to use eval in this case to force the shell to interpret the value of $(pyfg) with the normal shell evaluation mechanism:

eval aoeu "$(pyfg)"

How effectlively to call a bash function to another in a program

export -f remote_connect

You exported only one function. You have to export all that you use.

export RED GREEN YELLOW etc...
export -f remote_connect hostclr ok information etc...


Related Topics



Leave a reply



Submit