Linux shell編程筆記

Linux shell編程筆記

第一行
#!/bin/sh  # 指定腳本解釋器,這裏是用/bin/sh做解釋器的
cd ~     # 切換到當前用戶的home目錄

可以切換sh

[dev@szvphispra72471 ~]$ ls -l /bin/*sh
-rwxr-xr-x. 1 root root 1215888 Apr  1  2019 /bin/bash
-rws--x--x. 1 root root   68856 Apr  1  2019 /bin/chsh
lrwxrwxrwx. 1 root root       4 Apr  1  2019 /bin/csh -> tcsh
-r-x------. 1 root root     377 Apr  1  2019 /bin/euleros_kdump_do_post.sh
-r-x------. 1 root root     112 Apr  1  2019 /bin/euleros_kdump_do_pre.sh
-rwxr-xr-x. 1 root root    4632 Apr  1  2019 /bin/gettext.sh
-rwxr-xr-x. 1 root root      32 Apr  1  2019 /bin/hash
-rwxr-xr-x. 1 root root    4194 Apr  1  2019 /bin/instmodsh
lrwxrwxrwx. 1 root root      10 Apr  1  2019 /bin/ipmish -> openipmish
-rwxr-xr-x. 1 root root   68480 Apr  1  2019 /bin/jimsh
-rwxr-xr-x. 1 root root   68480 Apr  1  2019 /bin/lchsh
-rwxr-xr-x. 1 root root    3147 Apr  1  2019 /bin/lesspipe.sh
-rwxr-xr-x. 1 root root   69072 Apr  1  2019 /bin/openipmish
-r-x------. 1 root root    2235 Apr  1  2019 /bin/os_check_timezone_for_rsyslog.sh
-r-x------. 1 root root    3211 Apr  1  2019 /bin/os_rotate_and_save_log.sh
-rwxr-xr-x. 1 root root   37821 Apr  1  2019 /bin/rescan-scsi-bus.sh
-rwxr-xr-x. 1 root root    1543 Apr  1  2019 /bin/setup-nsssysinit.sh
lrwxrwxrwx. 1 root root       4 Apr  1  2019 /bin/sh -> bash
-rwxr-xr-x. 1 root root  790344 Apr  1  2019 /bin/ssh
-rwxr-xr-x. 1 root root   68632 Apr  1  2019 /bin/stapsh
lrwxrwxrwx. 1 root root       8 Apr  1  2019 /bin/tclsh -> tclsh8.6
-rwxr-xr-x. 1 root root  475064 Apr  1  2019 /bin/tcsh
-rwxr-xr-x. 1 root root  813328 Apr  1  2019 /bin/zsh

切換至sh腳本所在目錄

cd $(dirname "$0")
linux bash 中暫停

read也用作讀取鍵盤輸入

read -n1 -p "Press any key to continue..." 
read -p "Enter your name: " name

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-5a7AZR75-1589896483574)(C:\Users\w00448203\AppData\Roaming\Typora\typora-user-images\image-20200519115645294.png)]

Shell printf 命令

另一個用於輸出的命令是printf,下面的腳本中使用了printf的一些基本功能:

#!/bin/bash
#Filename: printf.sh

printf "%-5s %-10s %-4s\n" No Name Mark
printf "%-5s %-10s %-4.2f\n" 1 Sarath 80.3456
printf "%-5s %-10s %-4.2f\n" 2 James 98.9989
printf "%-5s %-10s %-4.2f\n" 3 Jeff 77.564

dash(即-)表示輸出左對齊,如果不加-,表示輸出右對齊。 dot 2(即.2)running off,精確到2位小數 slash n(即\n)換行符

Shell 傳遞參數 $
shell參數
變量	描述
$0	當前腳本的名字
$n	傳遞給腳本或者函數的參數,n是幾,代表第幾個參數
$#	輸入參數的個數
$*	輸入的所有參數的列表,使用雙引號括起來時,所有參數當做一個整體
$@	輸入的所有參數,使用雙引號時,每個參數一個個體
$?	上一個命令的執行結果,正確時返回0,不正確時返回非0
$$	當前進程的pid
Linux Shell——流程控制
Shell表達式
-b file	file 存在並且是一個塊(設備)文件。
-c file	file 存在並且是一個字符(設備)文件。
-d file	file 存在並且是一個目錄。
-e file	file 存在。
-f file	file 存在並且是一個普通文件。
Shell腳本調試選項

sh -x task.sh

Shell本身提供一些調試方法選項:

  • -n,讀一遍腳本中的命令但不執行,用於檢查腳本中的語法錯誤。
  • -v,一邊執行腳本,一邊將執行過的腳本命令打印到標準輸出。
  • -x,提供跟蹤執行信息,將執行的每一條命令和結果依次打印出來。

使用這些選項有三種方法(注意:避免幾種調試選項混用)

  • 1.在命令行提供參數:$sh -x script.sh
  • 2.腳本開頭提供參數:#!/bin/sh -x
  • 3.在腳本中用set命令啓用or禁用參數:其中set -x表示啓用,set +x表示禁用。
Shell文件包含,跨文件調用函數、變量

如何跨shell腳本文件調用函數

Shell 腳本調用另一個腳本的三種方法

Shell參考資料

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