Linux ·

shell编程中用户输入处理

shell编程中用户输入处理
1.命令行参数
2.脚本运行时获取输入

命令行参数 通过空格来进行分割的
位置参数 :+position  +position 0,1, 1, 2 ....
$0 :程序名
1, 1, 2,3... 3... 9
10及其以上的
${10}

add.sh

#/bin/bash
echo "file is $0"
echo "1->$1"
echo "2->$2"
echo "10->${10}"
echo "11->${11}" 

./add.sh 1 2 3 4 5 6 7 8 9 10 11
file is ./add.sh
1->1
2->2
10->10
11->11

$0表示 命令行输入的

/root/sh/f.sh

#! /bin/bash
echo `basename $0`
echo `dirname $0`
[root@localhost110 sh]# /root/sh/f.sh
f.sh
/root/sh

calc.sh

#! /bin/bash

name=`basename $0`

if [ $name = "add" ]
then
        result=[1+$2]
elif [ $name="minus" ]
then
        result=[1-$2]
fi
echo "the name result isresult"

注意if 后的[]与变量之间必须有空格

chmod u+x calc.sh

ln -s calc.sh add
ln -s calc.sh minus

执行命令

 ./add 1 2
the add result is 3
 ./minus 5 1
the minus result is 4

命令行参数-特殊变量
1.参数计数(参数个数):$#
2.所有参数: $*
3.参数列表: $@

test.sh

#! /bin/bash

echo $#
echo $*
echo $@
echo "#######################"
for var in "$*"
do
        echo "\* param=var"
done

echo "########################"

for var in "$@"
do
        echo "\@ param=var"
done

执行结果

[root@localhost110 sh]# ./test.sh 1 2 js php
4
1 2 js php
1 2 js php
#######################
$* param=1 2 js php
########################
$@ param=1
$@ param=2
$@ param=js
$@ param=php

参与评论