id

A Safer Way to Return the Current Username in Shell Script

Getting the current username, it sounds like a very easy task:

1
2
$ bash -c 'echo "$USER"'
chao

But depending on the environment variable is not reliable, it can be easily overridden:

1
2
$ USER=foo bash -c 'echo "$USER"'
foo

Or just simply fail to work:

1
$ docker run --rm bash:4.4.23 bash -c 'USER=foo echo "$USER"'

The USER environment was not set in /etc/profile in this case:

1
2
3
4
5
6
$ docker run --rm bash:4.4.23 bash -c 'cat /etc/profile'
export CHARSET=UTF-8
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PAGER=less
export PS1='\h:\w\$ '
umask 022

This is especially important when writing shell script. You do not want to end up with a wrong username.

One solution is to use whoami, which prints the effective user:

1
2
$ USER=foo bash -c 'whoami'
chao

Another solution is to use id command:

1
2
$ USER=foo bash -c 'id -un'
chao

This will eliminate the overridden environment variable issue. Also, check out this StackOverflow post for others and POSIX compatible means:

https://stackoverflow.com/questions/19306771/get-current-users-username-in-bash

Working with Big Number in JavaScript

JavaScript is only capable of handling 53-bit numbers, if you are working with a big number such as Twitter ID, which is using 64-bit number, then you need to find an external library to do that, otherwise, there will be precision lost:

> num = 420938523475451904
420938523475451900
> num = 420938523475451904 + 1
420938523475451900
> num = 420938523475451904 - 1
420938523475451900

Here is one library to use in Node environment, install Big.js:

$ npm install big.js

Load the module:

> BigNum = require('big.js')
{ [Function: Big] DP: 20, RM: 1 }

Use string to create the big number:

> num = BigNum('420938523475451904')
{ s: 1,
  e: 17,
  c: [ 4, 2, 0, 9, 3, 8, 5, 2, 3, 4, 7, 5, 4, 5, 1, 9, 0, 4 ] }
> num.toString()
'420938523475451904'

Perform addition:

> num.plus(1).toString()
'420938523475451905'

Perform substraction:

> num.minus(1).toString()
'420938523475451903'

There are other packages that yet to be tested: