手机版
你好,游客 登录 注册
背景:
阅读新闻

shell编程中用户输入处理

[日期:2016-11-17] 来源:Linux社区  作者:HKUI [字体: ]

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 is $result"

注意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

本文永久更新链接地址http://www.linuxidc.com/Linux/2016-11/137229.htm

linux
相关资讯       shell编程  shell用户输入处理 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款