[关闭]
@xtccc 2016-08-08T13:32:56.000000Z 字数 1663 阅读 2320

处理Script的参数

给我写信
GitHub

此处输入图片的描述

Shell



参考:


目录:


1. 遍历所有的参数


方法1: 不使用参数的位置

  1. # test.sh
  2. for var in "$@" ; do
  3. echo "$var"
  4. done

测试一下:

  1. # ./test.sh "a a a" b c d
  2. a a a
  3. b
  4. c
  5. d



"$@"表示所有的参数,注意$@两边的双引号是必须的,否则:

  1. # ./test.sh "a a a" b c d
  2. a
  3. a
  4. a
  5. b
  6. c
  7. d


实际上,for var in "$@"for var 是等效的,我们把script改一下:

  1. # test.sh
  2. for var; do
  3. echo "$var"
  4. done

测试:

  1. # ./test.sh "a a a" b c d
  2. a a a
  3. b
  4. c
  5. d



参看命令help for的解释:

# help for
for: for NAME [in WORDS ... ] ; do COMMANDS; done
Execute commands for each member in a list.
If in WORDS ...; is not present, then in "$@" is assumed.


方法2:使用参数的位置

  1. # test.sh
  2. for ((i = 1; i < $#; i++)); do
  3. echo ${!i}
  4. done

测试一下:

  1. # ./test.sh "a a a" "this is a \"double quote\"" c
  2. a a a
  3. this is a "double quote"
  4. c



解释:


另一种写法:将输入参数保存为数组

  1. # test.sh
  2. args=("$@") # 将全部的参数作为数组存储
  3. len=${#args[@]} # 数组的长度
  4. echo "args=${args[@]}" # 一次性输出数组的全部内容
  5. echo "len=$len"
  6. for ((i = 0; i < $len; i++)); do
  7. echo "args[$i]=${args[$i]}" # 通过位置来访问数组的各元素
  8. done

测试一下:

  1. # ./test.sh "a a a" b c
  2. args=a a a b c
  3. len=3
  4. args[0]=a a a
  5. args[1]=b
  6. args[2]=c



注意: echo ${args[@]} 输出数组的全部元素,而echo ${args}只能输出数组的首元素。



2. 参数含有空格及引号


如果参数含有空格,例如希望把a a a作为一个参数,则传参时使用"a a a";如果参数含有空格,例如真正的参数内容为this is "double quote",则传参时使用"this is \"double quote\""

我们依然使用之前的script:

  1. # test.sh
  2. for var in "$@"; do
  3. echo "$var"
  4. done



测试一下:

  1. # ./test.sh "a a a" "this is \"double quote\"" c d
  2. a a a
  3. this is "double quote"
  4. c
  5. d




3. shift


shift.sh文件

  1. #!/bin/bash
  2. echo "arg0=$0 arg1=$1 arg2=$2 arg3=$3 arg4=$4"
  3. shift
  4. echo "arg0=$0 arg1=$1 arg2=$2 arg3=$3 arg4=$4"
  5. shift
  6. echo "arg0=$0 arg1=$1 arg2=$2 arg3=$3 arg4=$4"
  7. shift
  8. echo "arg0=$0 arg1=$1 arg2=$2 arg3=$3 arg4=$4"



运行结果:

  1. # ./shift.sh 100 200 300 400 500
  2. arg0=./shift.sh arg1=100 arg2=200 arg3=300 arg4=400
  3. arg0=./shift.sh arg1=200 arg2=300 arg3=400 arg4=500
  4. arg0=./shift.sh arg1=300 arg2=400 arg3=500 arg4=
  5. arg0=./shift.sh arg1=400 arg2=500 arg3= arg4=
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注