
我寫了一個 shell 腳本,使用case
.代碼是:
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
當我運行此腳本時,輸出位於一行中,我希望它以柱狀格式顯示(即在單列中跨多行列出)。我已經嘗試過cut
、column
和sort
命令,但仍然沒有喘息的機會。輸出是:
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 ~]$
答案1
我會使用awk
而不是cut
為此,例如:
#!/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
執行樣本:
./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
正如您所看到的,輸出全部合而為一柱子,不在一條線上。
編輯:在 OS X 10.11.6 下測試
bash --version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)