一,shell 传参指的是 linux 命令参数传参给shell 程序
$0 相当于argv[0] 获取linux 命令 不带参数
$1、$2... 位置参数(Positional Parameter),python函数的argv[1]、argv[2]...
$# 获取所有的参数 个数
$@ 表示参数列表"$1" "$2" ...,例如可以用在for循环中的in后面。
$* 表示参数列表"$1" "$2" ...,同上
$? 上一条命令的Exit Status
$$ 当前进程号
shift 命令表示参数集体左移
#! /bin/sh
echo "The program $0 is now running"
echo "The first parameter is $1"
echo "The second parameter is $2"
echo "The parameter list is $@"
shift # 表示后面所有的参数都会左移一个
echo "The first parameter is $1"
echo "The second parameter is $2"
echo "The parameter list is $@"
![]()
二,shell 函数:
1,Shell中也有函数的概念,但是函数定义中没有返回值也没有参数列表
2,shell函数内同样是用$0、$1、$2等变量来提取参数
3,Shell脚本中的函数必须先定义后调用,也就是定义必须在调用的前面 这也是由于是解释语言的原因
4,return后面跟一个数字则表示函数的Exit Status
#! /bin/sh
#如果 传参是文件名 不是文件夹名称 那么返回
#没有形参列表 ()
is_directory()
{
DIR_NAME=$1
if [ ! -d $DIR_NAME ]; then
return 1
else
return 0
fi
}
for DIR in "$@"; do
#给函数传参
if is_directory "$DIR"
then :
else
echo "$DIR doesn't exist. Creating it now..."
#如果创建文件失败 错误信息打印到 /dev/null
# 2 文件描述符 错误信息stderr, 1 文件描述符 输出信息stdout, 0文件描述符 键盘输入 stdin
# 2>&1 也就是将错误信息输出到 /dev/null 别再给我打印出来了
mkdir $DIR > /dev/null 2>&1
if [ $? -ne 0 ]; then # -ne 不等于
echo "Cannot create directory $DIR"
exit 1
fi
fi
done