本週作業圍繞三件事打轉:用 vim 的末行模式做批次替換、用 sed 做串流編輯、用 for 迴圈把重複勞動自動化,最後再加上 crontab 排程。以下依題號整理操作與指令。
# cp /etc/rc.d/rc.sysinit /tmp # vim /tmp/rc.sysinit :%s/^[[:space:]]/#&/g
& 代表比對到的整段文字,所以這個替換等於在行首補一個 #。
# cp /boot/grub/grub.conf /tmp # sed 's@^[[:space:]]\+@@' /tmp/grub.conf
這裡用 @ 當分隔符,避免路徑裡的斜線造成混淆。
# sed 's/^#[[:space:]]\+//' /tmp/rc.sysinit
# sed -e "1,3s/^/#/" grub.conf
或用 vim::1,+2s/^/#&/g。結果如下:
## grub.conf generated by anaconda ## ## Note that you do not have to rerun grub after making changes to this file # NOTICE: You have a /boot partition.
# vim /etc/yum.repos.d/CentOS-Media.repo :/enabled=0/s/0/1/g :/gpgcheck=0/s/0/1/g
# crontab -e 0 */4 * * * /bin/cp -r /etc /backup/etc-`date +%Y%m%d%H%M`/
0 0 * * 2,4,6 /bin/cp /var/log/messages /backup/messages_logs/messages-$(date '+%Y%m%d')
# mkdir -p /stats && touch /stats/memory.txt 0 */2 * * * /bin/grep '^S' /proc/meminfo >> /stats/memory.txt
0 9-18/2 * * 1-5 /bin/echo "howdy"
#!/bin/bash tt=`date '+%Y-%m-%d_%H:%M'` && mkdir "/tmp/testdir-$tt" && ls -d /tmp/testdir*
#!/bin/bash
for n in {1..100}; do
[ -e "/tmp/file$n" ] || touch "/tmp/file$n"
done
原題若寫成 mkdir 會產生目錄而非檔案,這裡改用 touch 才符合「空檔案」的要求。
#!/bin/bash sed -n 'p;n' /etc/passwd | cut -d: -f1
p;n 是一印一跳,正好取出偶數行。
#!/bin/bash
for x in {10..19}; do
if ! id user$x &> /dev/null; then useradd user$x; fi
echo "user$x" | passwd --stdin user$x &> /dev/null
done
#!/bin/bash
for createfile in {10..19}; do
[ -e "/tmp/file$createfile" ] || touch "/tmp/file$createfile"
done
ls -l /tmp/file1[0-9]
#!/bin/bash
for i in {10..19}; do
grep -q "^user$i" /etc/group || groupadd "user$i"
id "user$i" &> /dev/null || useradd -g user$i user$i
chown user$i:user$i "/tmp/file$i"
done
執行後 ls -l /tmp/file1[0-9] 應可看到擁有者與群組已一一對應。這組練習的重點其實很單純:把「會重複的事」交給迴圈,把「會出錯的事」交給條件判斷。