1.設定變量FILE的值爲/etc/passwd
2.依次向/etc/passwd中的每一個用戶問好,而且說出對方的ID是什麼
形如:(提示:LINE=`wc -l /etc/passwd | cut -d" " -f1`)
Hello,root,your UID is 0.
3.統計一個有多少個用戶
答案一:#!/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"
答案二:#!/bin/bash
file=/etc/passwd
let num=0
for I in `cat $file`;do
username=`echo "$I" | cut -d: -f1`
userid=`echo "$I" | cut -d: -f3`
echo "Hello,$username,your UID is $userid"
num=$[$num+1]
done
echo "there are $num users"
練習二:寫一個腳本
1.切換工做目錄至/var
2.依次向/var目錄中的每一個文件或子目錄問好,形如:
(提示:for FILE in /var/*;或for FILE in `ls /var`;)
Hello,log
3.統計/var目錄下共有多個文件,並顯示出來
答案:#!/bin/bash
cd /var
let num=0
for I in `ls /var/*`;do
echo "hello $I"
num=$[$num+1]
done
echo "the number of files is $num"
練習三:寫一個腳本
1.設定變量file的值爲/etc/passwd
2.使用循環讀取文件/etc/passwd的第2,4,6,10,13,15行,並顯示其內容
3.把這些行保存至/tmp/mypasswd文件中
答案:#!/bin/bash
file="/etc/passwd"
for I in 2 4 6 10 13 15;do
exec 3>/tmp/mypasswd
line=`head -$I $file | tail -1`
echo "$line"
echo "$line" >&3
exec 3>&-
done
答案以下:vim test.sh
#!/bin/bash
echo "first number $1" (表示輸出第一個數)
echo " $(($1+$2))" (輸出兩數之和)
echo "$[$1-$2]" (輸出兩數之差)
echo "$[$1*$2]" (輸出兩數之積)
:wq (表示保存並退出vi編輯器)
chmod +x test.sh (給test.sh執行的權限)
./test.sh 2 3 (傳遞兩個參數並執行腳本
#!/bin/bash
mkdir -v /tmp/scripts
cd /tmp/scripts
cp -r /etc/pam.d ./test
chown -R redhat ./test
chmod -R o=--- ./test
#!/bin/bash
date
mkdir -pv /tmp/lstest
cd /tmp/lstest
mkdir a1d b56e 6test
touch xy x2y 732
ls [ax6]*
ls [[:alpha:]][[:digit:]]*