萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 執行 .sh 腳本文件的兩種常用方法與技巧

方法一:賦予執行權限並直接運行 (推薦)

  1. 打開終端 (Terminal)。
  2. 切換到腳本所在目錄:cd /path/to/script
  3. 添加執行權限:chmod +x script.sh
  4. 執行:./script.sh

示例:在 /tmp 目錄下運行 1.sh

$ cd /tmp
$ chmod +x 1.sh
$ ./1.sh

若腳本需要 Root 權限,可在命令前加 sudo:sudo ./1.sh。

方法二:直接調用 Shell 解析器

無需執行權限,直接指定解析器:

sh script.sh
# 或
bash script.sh

此方式下腳本首行 #!/bin/bash 等 Shebang 會被忽略,由指定的 Shell 解析。

常見問題與提示

  • 權限被拒絕:執行 chmod +x 或使用 sh script.sh。
  • 行尾符差異:Windows 編輯的腳本可能含 \r,用 dos2unix script.sh 或 sed -i 's/\r$//' script.sh 轉換。
  • 查看幫助:man sh 或 man bash 了解更多選項。
  • 調試模式:bash -x script.sh 逐行顯示執行過程。

總結

習慣使用 chmod +x + ./script.sh 可保留 Shebang 指定的解析器,更符合腳本可移植性原則;sh script.sh 適合快速測試或無寫入權限場景。

copyright © 萬盛學電腦網 all rights reserved