$cat test
#!/bin/bash
total=$[ $1 * $2 ]
echo The total value is $total.
$./test 25
The total value is 10.
shell参数可以是字符串,每个参数都是用空格分隔的,所以shell会将空格当成分隔两个值的分隔符
参数值中包含空格,必须要用引号(单引号双引号都可以)
#cat test#!/bin/bash
echo Hello $1, glad to meet you
$./test 'Rich Blum'
Hello Rich Blum, glad to meet you.
$
脚本需要多于9个命令行参数时,需要使用花括号({}),比如,${10}
13.1.2 读取程序名
$0:获取shell在命令行启动的程序的名字
当传给$0变量的真实字符串是整个脚本的路径时,程序中就会使用整个路径,而不仅仅是程序名
basename命令会只返回程序名而不包括路径
$cat test
#!/bin/bash
name=`basename $0`
echo The command entered is : $0echo The command entered is : name
$./test
The command entered is : ./test
The command entered is : test
$/home/rich/test
The command entered is : /home/rich/test
The command entered is : test
$
$cat test
#!/bin/bash
if [ $#-ne2 ]
thenecho Usage: test a b
else
total=$[ $1 + $2 ]
echo The total is $totalfi
$./test
Usage: test a b
$./test 10
Usage: test a b
$./test 1015
The total is 25
$./test 101520
Usage: test a b
$cat test
#!/bin/bash
while [ -n "$1" ]
docase"$1"in-a) echo"Found the -a option";;
-b) echo"Found the -b option";;
*) echo"$1 is not an option";;
esac
shift
done
$
$./test -a -c
Found the -a option
-c is not an option
$
$cat test
#!/bin/bash
while [ -n "$1" ]
docase"$1"in-a) echo"Found the -a option";;
-b) echo"Found the -b option";;
--) shift
break;;
*) echo"$1 is not an option";;
esac
shift
done
count=1for param in$@doecho"Parameter #$count: $param"
count=$[ $count + 1 ]
done
$
$./test -a test1
Found the -a option
test1 is not an option
$./test -a -- test1
Found the -a option
Parameter #1: test1
处理带值的选项
当命令行选项要求额外的参数时,脚本必须能检测并能正确的处理
$cat test
#!/bin/bash
while [ -n "$1" ]
docase"$1"in-a) echo"Found the -a option";;
-b) param="$2"echo"Found the -b option, with parameter value $param"
shift 2;;
-c) echo"Found the -c option";;
--) shift
break;;
*) echo"$1 is not an option";;
esac
shift
done
count=1for param in"$@"doecho"Parameter #$count: $param"
count=$[ $count + 1 ]
done
$
$./test -a -b test1 -d
Found the -a option
Found the -b option, with parameter value test1
-d is not an option
$
$./test -b test1 -a-d
Found the -b option, with parameter value test1
Found the -a option
-d is not an option
$
$cat test
#!/bin/bash
set -- `getopt -q ab:c "$@"`
while [ -n "$1" ]
docase"$1"in-a) echo"Found the -a option";;
-b) param="$2"echo"Found the -b option, with parameter value $param"
shift ;;
-c) echo"Found the -c option";;
--) shift
break;;
*) echo"$1 is not an option";;
esac
shift
done
count=1for param in"$@"doecho"Parameter #$count: $param"
count=$[ $count + 1 ]
done
$
$./test -a -b test1 -cd test2 test3
Found the -a option
Found the -b option, with parameter value 'test1'
Found the -c option
Parameter #1: 'test2'
Parameter #1: 'test3'