簡體   English   中英

將傳遞的參數存儲在單獨的變量-shell腳本中

[英]storing passed arguments in separate variables -shell scripting

在我的腳本“script.sh”中,我想將第一個和第二個參數存儲到某個變量中,然后將其余參數存儲到另一個單獨的變量中。 我必須使用什么命令來執行此任務? 請注意,傳遞給腳本的參數數量會有所不同。

當我在控制台中運行命令時

./script.sh abc def ghi jkl mn o p qrs xxx   #It can have any number of arguments

在這種情況下,我希望我的腳本在一個變量中存儲“abc”和“def”。 “ghi jkl mn op qrs xxx”應存儲在另一個變量中。

如果你只想連接參數:

#!/bin/sh

first_two="$1 $2"  # Store the first two arguments
shift              # Discard the first argument
shift              # Discard the 2nd argument
remainder="$*"     # Store the remaining arguments

請注意,這會破壞原始位置參數,並且無法可靠地重建它們。 如果需要,還需要做一些工作:

#!/bin/sh

first_two="$1 $2"  # Store the first two arguments
a="$1"; b="$2"     # Store the first two argument separately
shift              # Discard the first argument
shift              # Discard the 2nd argument
remainder="$*"     # Store the remaining arguments
set "$a" "$b" "$@" # Restore the positional arguments

切片$@數組。

var1=("${@:1:2}")
var2=("${@:3}")

將所有args存儲在表中

  vars=("$@")

  echo "${vars[10]}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM