已复制
全屏展示
复制代码

python与bash用法比较


· 1 min read

字符串startswith和endswith

  • Python
# startswith
if "BusFly".startswith("Bus"):
    print(True)

# endswith
if "BusFly".endswith("Fly"):
    print(True)
  • Bash
# startswith
if [[ "BusFly" = Bus* ]];then
	echo true
else
	echo false
fi

# endswith
if [[ "BusFly" = *Fly ]];then
	echo true
else
	echo false
fi

字符串contains包含

  • Python
"cd" in "abcdddd"
True
  • Bash
string='My long string'
if [[ $string == *" lon"* ]]; then
  echo "it contains."
fi

按行读取文件内容

  • Python
with open('/etc/profile') as f:
    for line in f:
        line=line.strip('\n')
        print(line)
  • Bash
    IFS(Internal Field Seprator) 表示内部域分隔符,默认为空格,这里在读取每一行的时候将其置空。read -r表示不转义任何字符。
while IFS= read -r line; do
     echo "$line"
done < /etc/profile

字符串split拆分

  • Python
with open('/etc/passwd') as f:
    for line in f:
        fields=line.split(":")
        print(fields[0], fields[-1])
  • Bash
# 方法一
while read name shell; do
    echo $name $shell
done < <(awk -F':' '{print $1,$NF}' /etc/passwd)


# 方法二:
# 注意:这里如果有远程登录执行命令,则必须要使用nohup后台执行,否则循环不会执行完。
awk -F':' '{print $1,$NF}' /etc/passwd | {
    while read name shell;do
        echo $name $shell
        nohup ssh host1 systemctl status firewalld &
        sleep 2
    done
}


# 方法三:
while read -r line;do
    readarray -d: -t arr <<< "$line"
    echo ${arr[0]} ${arr[6]}
done < /etc/passwd

# 方法四:
echo $my_str | tr ":" " "

数组追加元素

  • Python
arr=[]
arr.append("element1")
arr.append("element2")
arr.append("element3")
  • Bash
    ${#arr[@]}表示当前数组的长度
arr=()
arr[${#arr[@]}]=element1
arr[${#arr[@]}]=element2
arr[${#arr[@]}]=element3
🔗

文章推荐