I'm looking at a Bash file from the GitHub docs. Here's an excerpt:
agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
agent_start () {
(umask 077; ssh-agent >| "$env")
. "$env" >| /dev/null ; }
I have a number of questions about the coding choices. I'm not sure if this is messy code or there are reasons for the decisions made that I could learn about:
- What is the point of using
>|to force redirection to/dev/null? Isn'tnoclobberirrelevant with/dev/null? - Is there a purpose to adding a semicolon after the final line in each function? Does this in some way ensure code safety?
- What's going on with the weird parentheses formatting of the second function and the single line function for the other one? Is this just poor coding standards or are there shell scripting conventions that apply here? My instinct would be to uniformly format all functions for readability as follows:
function myfunc() {
# ...
}
I agree.
noclobberworks on regular files, and /dev/null is chardev, so it's unaffected. I would blame programmer habits, and it's no harm done, so it's fine. I could potentially argue that> /dev/nullis better than>| /dev/null, in case /dev/null is not a chardev on a malicious system then you'll get an error, but it's negligible.Commands are separated by newlines or semicolons in shell. A semicolon is needed before
}ending the{command grouping. For example:{ echo 1; echo 2; }.No.
Really nothing, it may be weird to you, may be not for the author. It's just one subshell on the first line which locally modifies umask, and then another command on the second line.
shfmtformats it as the following, which looks nicer to me.There are not really many shell coding styles standards, like https://google.github.io/styleguide/shellguide.html , so use common sense.
Running an
umask 077inside a subshell not to affect the parent shell and to create file not accessible by others is definitely great.For me, the standard would be to check your scripts with shellcheck.
function myfunc()is a mix of two syntaxes - ksh and sh. It's justmyfunc()in Bash, nofunction. Many people usefunctionin Bash because it's nice for readability, in fact it's not standard, but I think all todays POSIX shell implementations accept it.