适用于Bash编程初学者小例子 - 第二篇
去掉字符串前面的一个或多个空格。
#!/bin/bash
str="f810yunlong-3: Cache flushing complete. "
IFS=':' read -ra substrs <<< "$str"
NODE="${substrs[0]}"
MSG="${substrs[1]}"
TRIM_MSG= echo "$MSG" | sed -e 's/^[[:space:]]*//'
#Remove the leading spaces from the variable
TRIM_MSG=`echo $MSG | sed -e 's/^[[:space:]]*//'`
# Print the value of $Var after trimming
printf "%s \n" "$NODE"
printf "=%s=\n" "$TRIM_MSG"
判断一个字符串里是否包含有一个子字符串。
#!/bin/bash
str="f810yunlong-3: Cache flushing complete. "
if [[ "$str" == *"Cache flushing complete."* ]]
then
printf "One node cache flushed successfully!\n"
else
printf "[Error] "
printf "Error happened in one node on flushing inline dedupe index and queue flush! \n"
fi
遍历一个文件夹里的所有的zip文件,以各自的zip文件名为各自的目录名,逐个解压到指定的目录下。
#!/bin/sh
ZIPDIR="/ifs/yunlong_bash/dir_zips"
UNZIPDIR="/ifs/yunlong_bash/dir5"
printf "Entered path: $ZIPDIR.\n\n"
cd "$ZIPDIR"
for zip in *.zip
do
dirname=`echo $zip | sed 's/\.zip$//'`
printf "Directory name to extract this file is: %s.\n" $dirname
dirfullpath="$UNZIPDIR/$dirname"
printf "Directory full path to extract this file is:%s.\n" $dirfullpath
mkdir "$dirfullpath"
unzip $zip -d $dirfullpath
printf "\n\n"
done
经过检验成功!
遍历一个文件夹里所有的tar文件,以各自的文件名为目录名,逐个解压到指定的目录下。
#!/bin/sh
TARDIR="/ifs/yunlong_bash/tar_test/tars"
UNTARDIR="/ifs/yunlong_bash/tar_test/untars"
printf "Entered path: $TARDIR.\n\n"
cd "$TARDIR"
for tar in *.tar
do
dirname=`echo $tar | sed 's/\.tar$//'`
printf "Directory name to extract this file is: %s.\n" $dirname
dirfullpath="$UNTARDIR/$dirname"
printf "Directory full path to extract this file is:%s.\n" $dirfullpath
mkdir "$dirfullpath"
tar -xvf $tar -C $dirfullpathprintf "\n\n"
done
经笔者亲自运行检验通过。
终止脚本的进一步执行。
#!/bin/bash
printf "Script is executing."
exit
printf "Script is still executing after exit."
*一试便知,第二句的打印终端上看不到的,因为没被执行。
逐行读取一个文本文件,并将内容输出。
#!/bin/bash
filename="/home/yunlong/source_datasets.txt"
n=1while read line; do
# reading each line
echo "Line No. $n : $line"
n=$((n+1))
done < $filename
参考资料
===========
https://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash
https://linuxhint.com/trim_string_bash/