- echo常用方法
#/bin/bash
a=23
#直接输出
echo "hello"
#直接输出,手动换行
echo "hello \n"
#手动不换行
echo "hello \c"
#转义字符
echo " \" hello \""
#引用变量
echo "a is ${a}"
#输入字段写入指定文件
echo "echo \"wen jian shu ru\"" > ./test.sh
- printf常用方法,引用菜鸟的教程,可以看出此函数类似于格式化的功能
#!/bin/bash
# author:菜鸟教程
# url:www.runoob.com
# format-string为双引号
printf "%d %s\n" 1 "abc"
# 单引号与双引号效果一样
printf '%d %s\n' 1 "abc"
# 没有引号也可以输出
printf %s abcdef
# 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用
printf %s abc def
printf "%s\n" abc def
printf "%s %s %s\n" a b c d e f g h I j
# 如果没有 arguments,那么 %s 用NULL代替,%d 用 0 代替
printf "%s and %d \n"
- test函数常与if配合使用
-
数字控制判断
image.png
-
字符串判断
image.png
-
文件测试
image.png
例子1,遍历目录文件
#!/bin/bash
files=/apps/*
echo ${files}
for f in ${files[*]}
do
echo -e "第一个文件是${f}, \c"
if test -d ${f}
then
echo "是个目录文件"
else
echo "不是普通文件"
fi
done
结果
第一个文件是/apps/apache-maven-3.3.9, 是个目录文件
第一个文件是/apps/apache-maven-3.3.9-bin.tar.gz, 不是普通文件
第一个文件是/apps/a.txt, 不是普通文件
第一个文件是/apps/jekins-tomcat-8080, 是个目录文件
第一个文件是/apps/nexus-3.7.1-02, 是个目录文件
第一个文件是/apps/nexus-3.7.1-02-unix.tar.gz, 不是普通文件
第一个文件是/apps/sonatype-work, 是个目录文件
注意,遍历目录使用files=/apps/*方式引用对象,
获取文件名,可以用ls /目录方式
例子2 遍历文件内容
#/bin/bash
for line in `cat ./test.sh`
do
echo ${line}
done
显示结果
#!/bin/bash
files=/apps/*
echo
${files}
for
f
in
${files[*]}
do
echo
"第一个文件是${f},
\c"
if
test
-d
${f}
then
echo
"是个目录文件"
else
echo
"不是普通文件"
fi
done
网友评论