1. 程式人生 > >linux shell習題

linux shell習題

課件地址:https://wenku.baidu.com/view/bac2ff10f18583d0496459f3.html

1.測試環境變數:HOME,PWD,IFS等
2.測試位置變數:$$,$#,$0,$1,$2,$3,[email protected],$*,再測試當IFS=‘’和取消IFS時[email protected]和$*的輸出
3.使用if和case對“是否選修了Linux課程”的問題做出回答
4.列出當前目錄下包含sh檔案的詳細資訊
5.列出1~50之間的奇數
6.計算1+2+…+n

7.統計/etc目錄下的檔案數和目錄數
8.設計一函式使能只列指定目錄下的子目錄
9.設計一函式能實現向檔案追加記錄的功能(記錄由若干變數構成)
10.監控某個使用者是否登陸
11將指定目錄下的.txt檔案成批量地改名為 .doc

1~2

#!/bin/bash
endl() {
    echo -e "=======end===============\n"
}

echo $HOME; endl # => /c/Users/mdzz
echo $PWD; endl # => /c/Users/mdzz/Desktop/2018linux
echo $IFS; endl
echo $$,$#,$0,$1,$2,$3,[email protected],$*; endl # => 5544,0,exercise.sh,,,,,

2

#!/bin/bash
endl() {
    
echo -e "=======end===============\n" } list="we:are:champion" ifs_old=$IFS IFS=$':' for val in $list do echo "n=$val" done IFS=$ifs_old; endl ifs_old=$IFS IFS='' echo [email protected],$* IFS=$ifs_old echo [email protected],$*; endl

3

#!/bin/sh
echo "是否選修了Linux課程"
read yesorno
if [ "$yesorno" = "yes" ] then echo "Good." elif [ "$yesorno" = "no" ]; then echo "what a pity!" else echo "Sorry, $yesorno not recognized. Enter yes or no" exit 1 fi exit 0

4~7

#!/bin/bash
#####指令碼一######
#輸入絕對路徑,查詢包含.sh結尾的檔案及目錄輸出到file.tmp裡
# read -p "請輸入要查詢的目錄:" DIR
# find ${DIR} -name "*.sh" > file.tmp
#!/bin/bash
#####指令碼二#####
#輸入要查詢的目錄,如果檔案不存在建立檔案,如果存在退出
# read -p "請輸入要查詢的目錄:" DIR
# read -p "請輸入要建立的檔案:" FILENAME
# if [ -d $DIR ];then
# if [ ! -f $FILENAME ];then
# touch $FILENAME
# echo "${FILENAME} 建立成功"
# else
# echo "${FILENAME} 檔案已經存在"
# exit 0
# fi
# else
# echo "指定的目錄不存在!"
# fi

DIR=`ls -l`
# echo $DIR
ls -l *.sh

echo {1..50..2} # 羅列1 ~50的奇數

# 求 1+2+3+..+n
read -p "請輸入數字n;" N
sum=0
for ((i=1; i<=$N; i++));do
    sum=$(($i+$sum))
done
echo $sum

#統計當前目錄檔案數和目錄數
FILE_NUM=`find ./ -type f |wc -l` #統計檔案數
DIR_NUM=`find ./ -type d |wc -l` #統計目錄數
echo $FILE_NUM
echo $DIR_NUM

11

#!/bin/bash
for file in `ls | grep .txt`
do
    NEW_FILE=`echo $file`
    # ${string/substring/replacement} # substring可以是正則表示式
    NEW_FILE=${NEW_FILE/.txt/.doc}
    mv $file $NEW_FILE
done