=Start=
缘由:
最近在写一些功能性脚本,发现Bash中字符串的startwith/endwith/contain判断这些功能还是比较常用的,但Bash不像Python自带这些函数,所以需要自己整理总结一下,方便以后使用。
正文:
参考解答:
主要参考之前记录的文章:
&
- 字符串的判等应该使用「=」或「==」符号;
- 数字的判等才是使用「-eq」来进行(网上很多文章瞎写,也不验证一下……);
#!/bin/bash
# set -x
var="ixyzero.com is the best!"
function func_main() {
# if [ $# -gt 0 ]; then
# input="$1"
# else
# input="ixyzero.com"
# fi
input=${1:-"ixyzero.com"}
echo $input
# echo ${#input} # ${#input} 是 $input 变量的长度
if [ ${var:0:${#input}} = $input ]; then
echo "\"$var\" startwith $input"
else
echo "\"$var\" not startwith $input"
fi
}
func_main "$@"
=
# 测试/使用方法如下 #不带参数(使用默认值进行测试) $ bash sh_str_startwith.sh ixyzero.com "ixyzero.com is the best!" startwith ixyzero.com $ #主动传入参数1 $ bash sh_str_startwith.sh abc abc "ixyzero.com is the best!" not startwith abc #主动传入参数2 $ bash sh_str_startwith.sh i i "ixyzero.com is the best!" startwith i
&
#!/bin/bash
# set -x
var="ixyzero.com is the best!"
function func_main() {
# if [ $# -gt 0 ]; then
# input="$1"
# else
# input="ixyzero.com"
# fi
input=${1:-"best!"}
echo $input
# echo ${#input} # ${#input} 是 $input 变量的长度
if [ ${var:0-${#input}} = $input ]; then
echo "\"$var\" endwith $input"
else
echo "\"$var\" not endwith $input"
fi
}
func_main "$@"
=
$ bash sh_str_endwith.sh best! "ixyzero.com is the best!" endwith best! $ $ bash sh_str_endwith.sh best best "ixyzero.com is the best!" not endwith best $ $ bash sh_str_endwith.sh ! ! "ixyzero.com is the best!" endwith ! $
&
# 字符串包含判断
# returns OK if $1 contains $2
strstr() {
[ "${1#*$2*}" = "$1" ] && return 1
return 0
}
参考链接:
- Linux Shell脚本的字符串截取等操作
https://ixyzero.com/blog/archives/512.html - Shell条件测试
https://ixyzero.com/blog/archives/1225.html
=END=
《 “Bash中如何判断字符串是否以某个字符(串)开头、包含、结尾?” 》 有 2 条评论
纯 bash 实现的常用功能的方法收集
https://github.com/dylanaraps/pure-bash-bible
`
字符串
数组
循环
文件处理
文件路径
变量
转义
参数扩展
括号扩展
算术操作符
算术
trap捕获
性能
过时的语法
内部变量
终端相关的信息
转换
其它
`
Blind-Bash – bash 脚本混淆项目
https://github.com/Rizer0/Blind-Bash