英文:
Handling extglob in library scripts that are sourced at login
问题
The content you provided is already in English, so there is no need for translation. If you have any other questions or requests, please feel free to ask.
英文:
Having posted a question about debugging a bash script, the solution involved setting the command shopt -s extglob
.
I have been sourcing some library scripts at login for use interactively. I introspected the possibility of calling shopt -s extglob
at the beginning of each file and unsetting at the end of each file.
It was explained that I could use the current status of a shopt flag. The command shopt -p extglob
also outputs a string one can eval to get back the current setting.
Can I get some further elaborations and some tests and useful implementations I can check out?
答案1
得分: 0
以下是已翻译的内容:
savestate=$(shopt -p extglob) # 保存旧的 extglob 设置
shopt -s extglob # 启用 extglob
# 执行需要扩展 globbing 的操作
eval "$savestate" # 恢复旧的 extglob 设置
你可以将前两行放在脚本开头,将最后一行放在结尾。脚本的其余部分将是“执行某事”的部分。
英文:
The code would look something like this:
savestate=$(shopt -p extglob) # save old extglob setting
shopt -s extglob # enable extglob
# do something that requires extended globbing
eval "$savestate" # restore the old extglob setting
You could put the first two lines at the beginning of the script, and the last line at the end. The rest of the script would be the "do something" part.
答案2
得分: 0
我审视了在每个文件的开头调用 shopt -s extglob 并在每个文件的结尾取消设置的可能性。
你可以编写一个 `function`,类似于:
enable_extlob(){
if ! shopt -q extglob; then
shopt -s extglob
fi
}
disable_extglob(){
if shopt -q extglob; then
shopt -u extglob
fi
}
----
对于脚本/文件的开始和结束,类似于
extglob_boolean(){
if ! shopt -q extglob; then
shopt -s extglob
else
shopt -u extglob
fi
}
----
- 将其添加到脚本/文件的开头和结尾。
- 该函数检查是否未启用 extglob,如果是,则启用它,否则禁用它。
- 这样做的缺点是,如果你调用的脚本需要像 @Barmar 在他的评论中提到的 `extglob`,请确保你确实需要它。
英文:
> I introspected the possibility of calling shopt -s extglob at the beginning of each file and unsetting at the end of each file.
You could write a function
, something like:
enable_extlob(){
if ! shopt -q extglob; then
shopt -s extglob
fi
}
disable_extglob(){
if shopt -q extglob; then
shopt -u extglob
fi
}
For both start and end of the script/files, something like
extglob_boolean(){
if ! shopt -q extglob; then
shopt -s extglob
else
shopt -u extglob
fi
}
-
Add that at the beginning and at the end of your script/files.
-
The function checks if extglob is NOT on, enable it otherwise disable it.
-
The downside of this is if the script you're calling needs
extglob
like what @Barmar said from his comment post. So make sure you really need this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论