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?
Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.
Use the str. split() method with maxsplit set to 1 to split a string and get the first element, e.g. my_str. split('_', 1)[0] . The split() method will only perform a single split when maxsplit is set to 1 .
The whitespace characters consist of ' ' , '\t' , '\n' , '\r' , 'f' , etc. We can use the split() function to split a char sequence around matches of a regular expression. To split on whitespace characters, we can use the regex '\s' that denotes a whitespace character.
To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array. In the following program, we have taken a string and split it by space.
Another simple solution is cut
with custom delimiter:
user=$(who am I | cut -d ' ' -f1)
echo $user
Use bash
parameter-expansion 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
privileges, you can use this bash
environment-variable,
printf "%s\n" "${SUDO_USER}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With