歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> shell編程中用戶輸入處理

shell編程中用戶輸入處理

日期:2017/3/1 9:09:19   编辑: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 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

Copyright © Linux教程網 All Rights Reserved