简单shell 学习
Shell文件起始語句:#!/bin/bash或者#!/bin/sh
例如:
#! /bin/sh
#out a
a = “hello world”????????定義變量a 賦予語句”hello world”
Echo ${a} ?????????????echo 輸出后面變量信息
默認變量:
$#:輸入腳本的命令行參數個數
$*:所有命令行參數值
$0:命令本身(shell文件名)
&1:第一個命令行參數
$2:第二個命令行參數
入參判斷:
if [ $# -ne 3 ] ; then ????if判斷后面的方括號內側都要空格;判斷命令行參數個數是否=3
???( ?-eq ??) ?????????-ne:不等于;-eq等于
...
...
fi ???????????????????fi表示if判斷結束
?
?
整體實例:(先輸出一句話,然后對比參數個數,=3時做do,!=3時告知正確輸入格式)
#! /bin/sh
Echo “my name is tom”
If [ $# -ne 3 ] ; then
Echo “the way is $0 dirname1 dirname2 dirname3”
Exit 1
Elif [ $# -eq 3 ] ; then
Echo ?$1
Echo ?$2
Echo ?$3
Echo ?$*
Fi
For dir in $1 $2 $3
Do
Mkdir ?${dir} (創建和參數名相同的文件夾)
Cd ?${dir} (進入該文件夾)
Touch ?${dir}.txt (創建同名txt文件)
Echo ?“my name is tom”?> ${dir}.txt (向同名txt文件內輸入my name is tom)
Cd .. (返回上一層目錄)
Done
?
執行腳本文件:(查看結果)
[root@localhost 1013]# ./test.sh
my name is tom
the way is :./test.sh dirname1 dirname2 dirname3
?
[root@localhost 1013]# ./test.sh a b c
my name is tom
a
b
c
a b c
[root@localhost 1013]# ls
a ?b ?c ?test.sh
[root@localhost 1013]# cd a
[root@localhost a]# ls
a.txt
[root@localhost a]# cat a.txt
my name is tom
?
其余判斷:
-r: ???判斷是否為文件夾
-f: ???判斷是否為文件
Case: 類似switch語句做判斷, ;;相當于break
例1:
#! /bin/sh
Folder=/home
[ -r “$folder”?] ?&& echo “can read $folder”
[ -f “$folder”?] ?|| echo “this is not a file”
?
執行腳本:
[root@localhost 1013]# ./file.sh
can read /home
this is not a file
?
例2:
#! /bin/sh
Read key
Case ?${key} in
[A-Z] ) echo “uppercase letter”;;
[a-z] ) echo “lowercase letter”;;
[0-9] ) echo “number”;;
* ) echo “unkown”;;
Esac
?
?
執行腳本:
[root@localhost 1013]# chmod 777 case.sh
[root@localhost 1013]# ./case.sh
A
uppercase letter
?
[root@localhost 1013]# ./case.sh
a
lowercase letter
?
[root@localhost 1013]# ./case.sh
1
Number
?
[root@localhost 1013]#?./case.sh
!
unkown
?
總結
以上是生活随笔為你收集整理的简单shell 学习的全部內容,希望文章能夠幫你解決所遇到的問題。