Tuesday, November 2, 2021

[SOLVED] How to get the first element of a string split with space

Issue

I am trying to get the name of the user after su in a bash script. I used the following code:

user=`who am i`
#user <- "user4035     pts/0        2017-04-02 05:13 (my-hostname)"
userarray=($user)
#userarray <- ["user4035", "pts/0", "2017-04-02 05:13", "(my-hostname)"]
user=${userarray[0]}
#outputs "user4035"
echo $user

It works correctly, but is it possible to achieve the same result with less number of commands?


Solution

Use bash parameter-expnasion without needing to use arrays,

myUser=$(who am i)
printf "%s\n" "${myUser%% *}"
user4035

(or) just use a simple awk, command,

who am i | awk '{print $1}'
user4035

i.e. in a variable do,

myUser=$(who am i | awk '{print $1}')
printf "%s\n" "$myUser"

(or) if your script is run with sudo previleges, you can use this bash environment-variable,

printf "%s\n" "${SUDO_USER}"


Answered By - Inian