Stories

Detail Return Return

命令行參數如何傳遞給 bash 腳本 ? - Stories Detail

命令行參數也稱為位置參數,這些參數是運行時終端上的 shell 腳本所特有的。在命令行傳遞給 shell 腳本的每個變量都存儲在相應的 shell 變量中,包括 shell 腳本名稱。

在本教程中,我們將學習如何在 Linux 中向 bash shell 腳本傳遞命令行參數。

command-line-arguments

參數説明如下:

command-line-shell-variables

讓我們創建一個名為 arguments.sh 的 shell 腳本,它將顯示所提供的命令行參數,並計算參數的數量、第一個參數的值和腳本的進程 ID (PID)。

$ vi arguments.sh
#!/bin/bash
#This Script demonstrate the usage of command line arguments in bash script

echo "There are $# arguments pass at command line"
echo "The arguments supplied are : $*"
echo "The first command line argument is: $1"
echo "The PID of the script is: $$"

使用 chmod 命令為腳本分配可執行權限

$ chmod +x arguments.sh

帶參數執行腳本

$ ./arguments.sh Debian RockyLinux Ubuntu RHEL SUSE

腳本輸出如下

Pass-command-line-arguments-bash-script

在上面的腳本中,我們也可以使用 $@ 代替 $* 來獲取所有參數。這兩個變量之間的關鍵區別在於 $* 以單個字符串表示所有參數,而 $@ 以數組形式表示參數,或者 $@ 展開為多個參數。

$@ 總是優先使用,為了理解它們的區別,讓我們創建以下腳本。

$ vi arguments-new.sh
#!/bin/bash
echo "With *:"
for arg in "$*"
do
echo "<$arg>"
done
echo
echo "With @:"
for arg in "$@"
do
echo "<$arg>"
done

執行腳本並注意其中的區別

Arguments-Example-Bash-Script

我的開源項目

酷瓜雲課堂-開源知識付費解決方案

  • course-tencent-cloud(酷瓜雲課堂 - gitee倉庫)
  • course-tencent-cloud(酷瓜雲課堂 - github倉庫)
user avatar hankin_liu Avatar motianlun_5d0766992e67a Avatar damonxiaozhi Avatar savokiss Avatar cloud11y Avatar
Favorites 5 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.