shell指令碼快速入門

來源:互聯網
上載者:User

一、變數賦值

#!/bin/bash
a="hello world" # = 兩側不能有空格!
echo "a is $a"
unset a
echo "this is ${a}nd"           #變數最好用 {} 擴起來,避免混淆
declare -i num1=10
declare -i num2=20
declare -i num3=$num1+$num2

比較重要的命令:

ls  wc cp mv grep cut cat file read sort uniq expr find tee basename  dirname head tail sed awk 

 

二、流程式控制制

1.參數控制

#!/bin/bash
echo $1 $2           #參數名
echo $0            #程式名
echo $@            #在一個變數中列出所有參數 $*
echo $#            #參數個數
echo $$            #進程號
echo $?            #上一條單獨命令的退出狀態  

2.if 迴圈(各參數一定要用空格隔開!!)

#!/bin/bash
for day in 1 2 3 4 5 6 7
do
if [ $day = 6 -o $day = 7 ]
then
echo "$day is a nice day"
elif [ $day = 1 ]
then
echo "starting to work..."
fi
done

3.case

read -p 'Please input a num: ' num
case $num in
1)
echo 1;;
2)
echo 2;;
3 | 4)
echo 3 or 4;;
*)
echo 'other';;
esac

4.for

#!/bin/bash
read dir
if [ -d "$dir" -a -r "$dir" ]; then
file=$(ls $dir)

for filename in $file
do
if [ -u "$dir/$filename" ]; then
echo "$filename has uid"
ls -l "$dir/$filename"
fi
done
else
echo "sorry $dir does not exist or could not read"
fi

此例可輸入: /usr/bin

5.while

#!/bin/bash
read str
while [ "$str" != 'ubuntu' ]
do
echo 'not right'
read str
done
echo "you have guessed it !"

6.until 

#!/bin/bash
read str
until [ $str = 'quit' ]
do
echo 'keep on'
read str
done
printf "you have entered quit !\n"

 

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.