(Tips & Tricks) bash trick

January 30, 2014

bash and subshelling

When using pipes in bash the last command in the pipeline is executed in a sub shell…. (in contrast to i.e. ksh). This can be inconvenient if you i.e. set a variable which will never gets known in the parent shell 🙁

Luckily Felix pointed me to a nice trick: make the last pipe a “named pipe” (with <(cmd)) and no subshell is started!

See here the difference:

$ cat subshell.sh foo=bar echo "outside (parent shell) foo is: $foo" echo bar2 | while read foo do echo "in while (subshell!) foo is: $foo" done echo "outside (parent shell) foo is still: $foo" $ bash subshell outside (parent shell) foo is: bar in while (subshell!) foo is: bar2 outside (parent shell) foo is still: bar $
$ cat nosubshell.sh foo=bar echo "outside (parent shell) foo is: $foo" while read foo < <( cat ) do echo "in while (no subshell!) foo is: $foo" break done echo "outside (parent shell) foo is now: $foo" $ bash nosubshell.sh outside (parent shell) foo is: bar blaat in while (no subshell!) foo is: blaat outside (parent shell) foo is now: blaat $

"A much wittier reply came to mind immediately after I clicked the 'Send' button."

Powered by Wordpress. Theme by Shlomi Noach, openark.org
© 1997 - 2024 KwaLinux Trainingen | Algemene voorwaarden | KvK: 10147727 | BTW-id: NL001873211B65 | Disclaimer