1. 程式人生 > 其它 >11月9日Java學習

11月9日Java學習

1.什麼是shell指令碼

就是把很多的linux命令放在一個檔案一起從上到下執行

2.shell指令碼寫法

#!/bin/bash

表示使用bash

3.shell指令碼語法

read輸入

#!/bin/bash
echo "please input:"
read name
echo "your nmae" $name

也可以

#!/bin/bash
read -p "please input:"name age
echo "your nmae" $name

數值計算

#!/bin/bash
read -p "please input:"first second
total=$($first + $second) //=兩邊不能用空格
echo "$first + $second = $total " 

test

用於檢視檔案是否存在、許可權等資訊,可以進行數值,字元,檔案三方面的測試
cmd1 && cmd2
並不是與的關係,是先執行cmd1,成功了執行cmd2,如果cmd1執行失敗了,則cmd2也不會執行
cmd1 || cmd2 當cmd1執行正確就不執行cmd2,如果cmd1錯誤就cmd2

#!/bin/bash
echo "please input filename: "
read -p "file name = " filename
test -e $filename && echo "$filename exist" || "$filename no exist"

檢視兩個字串是否相等:

#!/bin/bash
echo "please input string: "
read -p "first string = " first
read -p "second string = " second
test $first == $second && echo "equal" || " no equal"

-e 檢視檔名,存在就為真

[]判斷符

#!/bin/bash
echo "please input string: "
read -p "first string = " first
read -p "second string = " second
[ "$first" == "$second" ] && echo "equal" || " no equal"

中括號兩端必須加空格!
字串必須加雙引號:
假如改成
[ $first == "a b" ] && echo "equal" || " no equal"
first = a b
就變成 a b == "a b"前面的a就沒關係了

預設變數

$0 - $n:表示shell指令碼的引數,包括他自己本身。shell本身為0
$# : 表示最後一個引數標號
$@: 表示1---n

#!/bin/bash
echo "file name: " $0
echo "total param num: " $#
echo "whole param : " $0
echo "first param : " $1
echo "second param : " $2

if

#!/bin/bash
read -p "please input : " value

if [ "$value" == "Y" ] || [ "$value" == "y" ]; then
   echo "Y"
   exit 0
fi

elif [ "$value" == "N" ] || [ "$value" == "n" ]; then
   echo "n"
   exit 0
fi

else 
   echo "?"
   exit 0
fi

case

#!/bin/bash
read -p "please input : " value

case $1 in 
	"a")
		echo " = a"
		;;
	"b")
		echo " = b"
		;;
	*) //其他,不能用雙引號
		echo "no"
		;;
esac

函式

function fname(){
	//函式程式碼段
}
#!/bin/bash

function help(){
	echo "this is help"
}
function close(){
	echo "close!"
}
case $1 in 
	"h")
		help
		;;
	"c")
		close
		;;
	*) 
		echo "no"
		;;
esac

傳參的時候加 -h或者-c

#!/bin/bash

function print(){
	echo "param 1 $1"
	echo "param 2 $2"
	echo "param 3 $3"
}
print a b c //這樣傳參

迴圈

while:

#!/bin/bash

while [ "$value" != "close" ]
do
	read -p "input:" value
done

echo "stop"

for:

#!/bin/bash

for name in szm szm1 szm2
do
	echo "your name" name
done
#!/bin/bash

read -p "input:" count
total = 0
for((i = 0; i <= count; i = i+1))
do
	total=$(($total + $i))
done

echo "total = " $total
主要是給自己看的,所以肯定會出現很多錯誤哈哈哈哈哈