bash 6-10

Lesson 6: If statement
#!/bin/bash
MYNUM=100
if [ $MYNUM -eq 200 ]
then
echo “MYNUM is equal to 200.”
else
echo ” MYNUM is not equal to 200”
fi
\=======================================
Lesson 7: Checking the Existense of Files and Folders
*touch myfile(不存在的文件會被create,如果有該文件,會改變最後修改時間)
*rm myfile(刪除文件)
*mkdir myfolder(建立新文件夾)
*rm -r myfolder(刪除文件夾)

ex:
nano number7 #建立一個名爲number7的文件
#!/bin/bash
if [ -d ~/myfolder ] #-d for directory,檢查myfolder文件夾是否存在;[ -f ~/myfile ]檢查myfile文件是否存在
then
echo “The folder exists.”
else
echo “The folder doesn’t exit.”
end
chmod +x number7 #使number7成爲可執行文件
./number7 #運行number7
\=======================================
Lesson 8: Universal Update Script

nano updatescript
#!/bin/bash
cd /etc
# Test if the local host is Arch-based
if [ -d /etc/pacman.d ]
then
# Run the Arch version of the update command
sudo pacman -Syu # Run Arch-based 系統的update代碼
fi #close if commond
# Test if the local host is Debian-based
if [ -d /etc/apt ]
then
# Run the Debian version of the update commond
sudo apt-get update && sudo apt-get dist-upgrade -y
fi
\=======================================
Lesson 9:Standard Input, Output, & Error
ls -l
cat
ls -l > filelist.txt #將ls -l的顯示內容保存到filelist.txt
ls -l > /dev/null #dev/null是個黑洞,如果扔文件進去,相當於刪除了
ls > file.txt #replace file.txt的內容
ls >> file.txt #將內容複製到file.txt結尾
———————————————————————————–
nano standardinputtest
#!/bin/bash
echo “Please enter your name:”
read myname #將輸入的文字存入變量myname
echo “You entered: $myname”
—————————————————————————————-
ls /root # 會出error
ls /root 2> errors.txt #0 standard input, 1 standard output, 2 standard error
\=======================================
Lesson 10:Creating a While loop
nano whiletest
#!/bin/bash
myval=1
while [ $myval -le 10 ] n #-le <=
do
echo $myvar
myvar=$(($myvar+1))
sleep 0.5
done
—————————————————————————————————
$0就是該bash文件名
$?是上一指令的返回值
$*所有位置參數的內容:就是調用調用本bash shell的參數。
$@基本上與上面相同。只不過是
$*”返回的是一個字符串,字符串中存在多外空格。
$@”返回多個字符串。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章