Take a look at the /etc/passwd . This file shows how user information is stored. User information may or may not be saved here. (There are several different databases that Unix uses to store users), but the format is the same.
Basically, Unix uses a user identifier (UID) to store what a user is. The next entry was the old password entry, followed by the UID, the primary group identifier, GECOS , the $HOME directory, and the user shell. (There are three additional entries displayed in the id -P command on MacOS. I don't know what it is, but they make the GECOS field an eighth field instead of a fifth field).
Using the id -P command on your system, you received this entry. Some systems use getent or even getpwent as a command. What you need to do is parse this entry. Each field is separated by colons, so you need either the fifth or the eighth record (depending on the command you should have used).
The awk and cut commands do this pretty well. cut is probably more efficient, but awk more common, so I try to use it.
In awk standard field separator is a space, but you can use the -F option to change this. In Awk, each field in a string is given a number and is preceded by a dollar sign. The $0 field is the entire line.
Using awk , you will get:
id -P | awk -F: '{print $8}'
This means taking the id -P command and using : as a field separator and printing the eighth field. Skin braces surround all AWK programs, and single quotes are needed to interpret the $8 shell.
In BASH, you can use $( ) to run the command and return its output so that you can set the environment variables:
$USER_NAME=$(id -P | awk -F: `{print $8}`) echo $USER_NAME
David W.
source share