#!/bin/bash
# Call this script with at least 10 parameters, for example
# ./scriptname 1 2 3 4 5 6 7 8 9 10
MINPARAMS=10
echo
echo "The name of this script is \"$0\"."
# Adds ./ for current directory
echo "The name of this script is \"`basename $0`\"."
# Strips out path name info (see 'basename')
echo
if [ -n "$1" ] # Tested variable is quoted.
then
echo "Parameter #1 is $1" # Need quotes to escape #
fi
if [ -n "$2" ]
then
echo "Parameter #2 is $2"
fi
if [ -n "$3" ]
then
echo "Parameter #3 is $3"
fi
# ...
if [ -n "${10}" ] # Parameters > $9 must be enclosed in {brackets}.
then
echo "Parameter #10 is ${10}"
fi
echo "-----------------------------------"
echo "All the $# command-line parameters are: "$*""
if [ $# -lt "$MINPARAMS" ]
then
echo
echo "This script needs at least $MINPARAMS command-line arguments!"
fi
echo
test="pwd"
echo $test
echo "$test"
echo `$test`
echo `pwd`
exit 0
运行:
./ex17.sh pwd 2 3 4 5 6 7 8 9 15
结果:
The name of this script is "./ex17.sh".
The name of this script is "ex17.sh".
Parameter #1 is pwd
Parameter #2 is 2
Parameter #3 is 3
Parameter #10 is 15
-----------------------------------
All the 10 command-line parameters are: pwd 2 3 4 5 6 7 8 9 15
pwd
pwd
/home/shell
/home/shell
本文详细解析了一个bash脚本如何通过命令行参数获取输入,并进行基本的字符串输出和参数验证。脚本展示了如何从命令行读取至少10个参数,包括对参数的简单打印和检查参数数量是否符合预期,同时演示了使用当前目录路径和脚本名的基本操作。
&spm=1001.2101.3001.5002&articleId=8122046&d=1&t=3&u=d5c77347d0484d9fb4500336e6c38cd8)
2920

被折叠的 条评论
为什么被折叠?



