1. 程式人生 > >shell腳本練習

shell腳本練習

shell 腳本

新手寫的shell,寫的不好,請大家見諒。

希望結交一些大神和同行。QQ:86416192 歡迎大家加QQ。

1、寫一個腳本,顯示出來多少個用戶,並且顯示出來每個用戶的ID。

#!/bin/bash


file="/etc/passwd"

LINES=`wc -l $file | cut -d" " -f1`

for I in `seq 1 $LINES`;

do

userid=`head -$I $file | tail -1 |cut -d: -f3`

username=`head -$I $file | tail -1 |cut -d: -f1`

echo "hello $username,your UID is $userid"

done

echo "there are $LINES users"


測試結果

[[email protected] scripts]# sh test.sh

hello root,your UID is 0

hello bin,your UID is 1

hello daemon,your UID is 2

hello adm,your UID is 3

hello lp,your UID is 4

hello sync,your UID is 5

hello shutdown,your UID is 6

hello halt,your UID is 7

hello mail,your UID is 8

hello operator,your UID is 11

hello games,your UID is 12

hello ftp,your UID is 14

hello nobody,your UID is 99

hello avahi-autoipd,your UID is 170

hello systemd-bus-proxy,your UID is 999

hello systemd-network,your UID is 998

hello dbus,your UID is 81

hello polkitd,your UID is 997

hello abrt,your UID is 173

hello tss,your UID is 59

hello postfix,your UID is 89

hello sshd,your UID is 74

hello rsync,your UID is 1000

hello chrony,your UID is 996

there are 24 users




2、在根目錄下有四個文件m1.txt,m2.txt,m3.txt,m4.txt,用Shell編程,實現自動創建m1,m2,m3,m4四個目錄,並將m1.txt,m2.txt,m3.txt,m4.txt四個文件分別拷貝到各自相應的目錄下。

#!/bin/bash

cd /

touch m1.txt m2.txt m3.txt m4.txt

I=1

while [ $I -le 4 ]

do

mkdir m$I

cp m$I.txt m$I

I=$((I+1))

done




3、編寫一個名為myfirstshell.sh的腳本,它包括以下內容。

a) 包含一段註釋,列出您的姓名、腳本的名稱和編寫這個腳本的目的。

b) 問候用戶。

c) 顯示日期和時間。

d) 顯示這個月的日歷。

e) 顯示您的機器名。

f) 顯示當前這個操作系統的名稱和版本。

g) 顯示父目錄中的所有文件的列表。

h) 顯示root正在運行的所有進程。

i) 顯示變量TERM、PATH和HOME的值。

j) 顯示磁盤使用情況。

k) 用id命令打印出您的組ID。

m) 跟用戶說“Good bye”



#!/bin/bash

echo "李松陽編寫"

user=`whoami`

case $user in

root)

echo "hello root";;

teacher)

echo "hello teacher";;

*)

echo "hello $user,welcome"

esac echo "日期和時間: `date`"

echo "本月的日歷: `cal`"

echo "本機的機器名:`uname -n`"

echo "當前這個操作系統的名稱和版本:`uname -s;uname -r`"

echo "父目錄中的所有文件的列表:`ls ../`"

echo "root正在運行的所有進程:` ps -u root`"

echo "變數TERM的值:$TERM"

echo "變數PATH的值:$PATH"

echo "變數HOME的值:$HOME"

echo "磁盤的使用情況:`df`"

echo "用id命令打印出你的組ID:`id -g`"

echo "Good bye!"




4、設計一個Shell程序,在/userdata目錄下建立50個目錄,即user1~user50,並設置每個目錄的權限為 rwxr-xr—


#!/bin/bash


if [ -d /userdata ]

then

cd /userdata

else

mkdir -p /userdata && cd /userdata

fi


I=1


while [ $I -le 50 ]

do

mkdir -p user$I

chmod 754 user$I

I=$((I+1))

done


5、編寫shell程序,實現自動創建50個用戶賬號的功能。賬號名為stud1至stud50。

#!/bin/bash


I=1


while [ $I -le 50 ]

do

useradd stud$I

I=$((I+1))

done


6、編寫shell程序,實現自動刪除50個用戶賬號的功能。賬號名為stud1至stud50。

[[email protected] scripts]# cat test06.sh

#!/bin/bash


I=1


while [ $I -le 50 ]

do

userdel stud$I

I=$((I+1))

done


本文出自 “李松陽” 博客,請務必保留此出處http://lsy666.blog.51cto.com/11729318/1957270

shell腳本練習