常用shell变量内容的操作

#!/bin/bash
echo "---------变量内容的截取-----------"
path=/home/pikaqiu/bin:/home/pikaqiu/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

# 示例1 删除包含第一个:左边的字符串
echo -n "output1: "
echo ${path#*:}

# 示例2 只保留/snap/bin
echo -n "output2: "
echo ${path##*:}

# 示例3 删除最后一个:及其右边的字符串
echo -n "output3: "
echo ${path%:*}

# 示例4 只保留/home/pikaqiu/bin
echo -n "output4: "
echo ${path%%:*}

# 总结:
# ------------- #  从左往右,删除第一个匹配到的字符串及其左侧的所有字符
#-------------- ## 从左往右,删除最后匹配到的字符串及其左侧的所有字符
#-------------- %  从右往左,删除第一个匹配到的字符串及其右侧的所有字符
#-------------- %% 从右往左,删除最后匹配到的字符串及其右侧的所有字符

# 简单记忆:
# #左往右删,%右往左删,符号越多,要求尽可能地多删。

echo "========变量部分内容取代功能============="
# 还是以我们的path来举例
# 示例5 从左到右,替换遇到的第一个bin为大写BIN
echo -n "output5: "
echo ${path/bin/BIN}

# 示例6 替换所有的bin为大写BIN
echo -n "output6: "
echo ${path//bin/BIN}

echo "========变量内容的整体替换功能============"
# 示例7 -的用法
username=""
echo "username=$username"            # username为空字符串
username=${username-root}            # 表示只要有值不管是否为空,则值不变
echo -n "output7.1: "
echo "username=$username"

unset username						# 取消username的定义
username=${username-root}
echo -n "output7.2: "
echo "username=$username"

# 示例8 :-的用法
# 如果username不存在或者为空字符串,都直接替换:-后的内容
username=""
username=${username:-root}
echo -n "output8.1: "
echo "username=$username"

unset username						# 取消username的定义
username=${username-root}
echo -n "output8.2: "
echo "username=$username"

 

输出信息如下:
---------变量内容的截取-----------
output1: /home/pikaqiu/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
output2: /snap/bin
output3: /home/pikaqiu/bin:/home/pikaqiu/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
output4: /home/pikaqiu/bin
========变量部分内容取代功能=============
output5: /home/pikaqiu/BIN:/home/pikaqiu/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
output6: /home/pikaqiu/BIN:/home/pikaqiu/.local/BIN:/usr/local/sBIN:/usr/local/BIN:/usr/sBIN:/usr/BIN:/sBIN:/BIN:/usr/games:/usr/local/games:/snap/BIN
========变量内容的整体替换功能============
username=
output7.1: username=
output7.2: username=root
output8.1: username=root
output8.2: username=root

 

你可能感兴趣的:(shell)