-2

I have written a shell script that displays username, terminal name, login time etc using case. The code is:

echo "Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time"
read ch
case $ch in
1)
echo `who | cut -c1-8 | cut -d" " -f1`
;;
2)
echo `who | cut -c9-16 | column`
;;
3)
echo `who | cut -c22-32 | sort`
;;
4)
echo `who | cut -c34-39`
;;
esac

When I run this script the output comes in a single line and I want it to be displayed in a columnar format (i.e. listed across multiple lines in a single column). I have tried the cut, column and sort commands, and yet no respite. The output is:

Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
1
bioinfo class class class class class class class class class class
[class@bio ~]$
terdon
  • 242,166
  • 1
    see if this helps: http://unix.stackexchange.com/questions/308631/how-to-process-a-multi-column-text-file-to-get-another-multi-column-text-file – Sundeep Oct 03 '16 at 07:37
  • 2
    Please [edit] your question and clarify. What is class and why is it repeated so many times? How did you run the script? Which option did you choose to get this output? Why are you using echo for commands that print their output to stdout anyway? – terdon Oct 03 '16 at 08:33
  • It is pretty clear that class is the username, result obtained after using the who command. – user3382203 Oct 04 '16 at 05:54

1 Answers1

2

I would use awk instead of cut for this, e.g.:

#!/bin/bash

echo "Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time"
read ch
case $ch in
    1)  
    who | awk '{ print $1 }'
    ;;  
    2)  
    who | awk '{ print $2 }'
    ;;  
    3)  
    who | awk '{ print $3 " " $4 }'
    ;;  
    4)  
    who | awk '{ print $5 }'
    ;;  
    *)  
    echo "Wrong input"
esac

Execution samples:

./whoList.sh 
Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
2
console
ttys000
ttys001

./whoList.sh 
Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
3
Oct 3
Oct 3
Oct 3

./whoList.sh 
Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
1
maulinglawns
maulinglawns
maulinglawns

./whoList.sh 
Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
4
09:01
09:44
11:01

./whoList.sh
Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
7
Wrong input

The output, as you can see, is all in one column, not on a single line.

Edit: Tested under OS X 10.11.6

bash --version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)