linux下的bash shell记录

更新时间 🔔🕙 2024年6月10日
# 删除变量A开头的文件
A=123
B=/path/to/directory
# 删除以变量A的值开头的所有文件
rm -f "${B}/${A}"*
# ⚠️注意,rm -f "${B}/${A}*"只会删除【/path/to/directory/123*】这一个文件
# 判断文件夹是否存在
if [ -d "/tmp/a" ]; then
    echo "folder exist"
else
    echo "folder not exist"
fi
# 判断文件是否存在
if [ -f "/tmp/a/1.txt" ]; then
    echo "file exist"
else
    echo "file not exist"
fi
# 检查文件夹是否存在(否定)
if [ ! -d "$folder" ]; then
    echo "The folder does not exist."
fi
# 判断变量是否为true(这是因为bash里面没有boolean变量,都是数字或者字符串)
if [ "${my_var}" = "true" ]; then
    echo "Variable is true"
else
    echo "Variable is false"
fi
# 判断字符串是否相等
string1="hello"
string2="world"
 
if [ "$string1" == "$string2" ]; then
  echo "字符串相等"
else
  echo "字符串不相等"
fi
# 使用 while 循环逐行读取文件内容并打印
while IFS= read -r line; do
  echo "Original: $line"
  # 删除行首的空格和Tab
  line=$(echo "$line" | sed "s/^[ \t]*//")
  # 判断是否为shell的注释行
  if [ "${#line}" -gt 1 ] && [ "${line:0:1}" != "#" ]; then
    echo "Trimmed: $line"
  else
    echo "这一行以#开头,忽略,跳过执行"
  fi
done < "./tts-text.txt"
# bash shell命令有时候太长,这个时候可以换行书写
python3 ./xxx.py --url "xxx" \
  -text "你好啊"
# 将一行内容分别赋值给不同变量
output="1 # 2 #  # 4"
IFS=" # " read -r v1 v2 v3 v4 <<< "$output"
转载请备注引用地址:编程记忆 » linux下的bash shell记录