0

i was just looking into a script i find this line. can anyone tell me what this line do. this is the code line.

[ -r "$PosConfigDir/posconfig.sh" ] && . "$PosConfigDir/posconfig.sh"
5

It checks whether you have permission to read the file $PosConfigDir/posconfig.sh, after symlink resolution, then sources that file.

It does not guarantee that you can read the file. For example, on most systems, [ -r / ] would return true but you cannot read /.

-r is a standard test operator.

. is a special builtin command of Bourne-like shells that tells the shell to read and interpret the code in the file given as argument. source is the equivalent command in csh. Many modern Bourne-like shells understand source as an alias for ..

With some shell implementations, the failure of . to open or read the file would cause the shell to abort (after having output an error message). The -r check is presumably meant to prevent that in that case.

To prevent the shell from aborting, in POSIX shells, an alternative could be

 command . "$PosConfigDir/posconfig.sh"

(Though the above construct won't work in zsh unless in sh or ksh emulation)

To avoid the error message, you'd need to redirect the stderr output to /dev/null, but that would have the unwanted side-effect of also silencing the errors of the commands in postconfig.sh.

An example:

$ [ -r /etc/os-release ] && . /etc/os-release
$ printf '%s\n' "$PRETTY_NAME"
Debian GNU/Linux 8 (jessie)

PRETTY_NAME was defined in /etc/os-release file:

$ head -n 1 /etc/os-release 
PRETTY_NAME="Debian GNU/Linux 8 (jessie)"
  • oh it means if that file is readable then use some of the functionality from that file. right! – The Bharat Mar 7 '16 at 10:28
  • @TheBharat: Yes, read more about dot command. – cuonglm Mar 7 '16 at 10:30
  • Note that -r only checks that you have permission to read the file (after symlink resolution). That doesn't guarantee that you'll be able to read it. For instance, [ -r / ] returns true, but on most systems, you won't be able to read(2) / (. would still fail). – Stéphane Chazelas Mar 7 '16 at 13:00
  • @StéphaneChazelas: Thanks, updated the answer. I remembered you have noticed me before, just don't have time to update the answer. Is it better now – cuonglm Mar 7 '16 at 13:10
  • @StéphaneChazelas: command . does not work with zsh unless in sh or ksh emulation. – cuonglm Mar 7 '16 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.