Bash subshell for setting SHELLOPTS in a script

雨燕双飞 提交于 2019-12-07 20:54:00

问题


This question is not cygwin specific. However, in the cygwin mail archive https://cygwin.com/ml/cygwin-announce/2010-08/msg00015.html are various instructions for setting the cygwin specific igncr shellopt variable and one of them is the instruction:

4a. For a single affected script, add this line just after the she-bang: ~ (set -o igncr) 2>/dev/null && set -o igncr; # comment is needed

I understand that set -o igncr sets igncr in SHELLOPTS. However, I do not understand why the instruction also includes invoking it in a subshell. From what I understand, the variables and environment of the subshell do not stick around in the parent process. What is the use of it?


回答1:


The detail that is material here in this command

(set -o igncr) 2>/dev/null && set -o igncr

is the context.

Imagine a shell script designed to run on non-Windows machines as well as in cygwin.

Normally (not under cygwin) the use of set -o igncr would be an error (as is attempting to set any other invalid set option.

However, under cygwin that set is both meaningful and helpful.

So how do you write a script that operates in both places? You need a test for the current environment. You could check for specific environment variables, specific paths, etc. or (and this is similar to the move away from browser-sniffing and to feature testing) you can just check whether the current environment supports the option you are attempting to set.

So try to set it but that throws an error if it doesn't work so try to set it in a sub-shell (and toss the error output to /dev/null to ignore it) and then if (and only if) that set succeeds (&&) then do the set in the current shell environment as well.



来源:https://stackoverflow.com/questions/30181046/bash-subshell-for-setting-shellopts-in-a-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!